顯示具有 C語言 標籤的文章。 顯示所有文章
顯示具有 C語言 標籤的文章。 顯示所有文章

2011年2月25日 星期五

使用IAR的strchr函數注意事項

最近使用IAR的strchr要搜尋字串字,某個字元出現的位置,但是明明該字元有存在,卻是搜尋不到,後來用一個for loop去一個一個搜尋終於可以了。上網找了一下strchr的implention,發現有幾種版本:

standard C:


char *strchr(const char *s, int c)
{
    while (*s != (char)c)
        if (!*s++)
            return 0;
    return (char *)s;
}


public-domain:


char *(strchr)(const char *s, int c)
 {
     /* Scan s for the character.  When this loop is finished,
        s will either point to the end of the string or the
        character we were looking for.  */
     while (*s != '\0' && *s != (char)c)
         s++;
     return ( (*s == c) ? (char *) s : NULL );
 }

我想IAR應該是使用public-domain的,所以一旦s裡面有\0,就立即跳出來了!
因此使用strchr、strrchr這一類函數時,要留意傳入的資料中,是否含有0x00,也就是null。如果傳入的資料含有0x00,搜尋出來的結果可能有錯。

2010年11月29日 星期一

switch case and watchdog

1.如果在switch case中,需等候I/O腳位變化,而決定是否往下執行,
可以把while(status)改寫成if (! status) then step++,避免程式卡在while loop,浪費時間,step中的watchdog也可以不需要去控制。

2.避免有以下寫法:

switch (step)
{
    case 0:
        WDT_stop();
        .......
        step++;
        break;
  
    case 1:
       .......
       step++;
       break;

    case 2:
      ......
      WDT_restart();
      break;
}

在step0到1的過程當中,WDT已經在main()又被開啟了,因此程式容易有不可預期的情形產生。

2010年11月17日 星期三

malloc使用注意

malloc使用時,要注意是否會超過heap size,尤其是function call function時,很容易超過,造成程式死當。