Wednesday, March 23, 2011

Error prone C

These tips taken from "writting solid code":misspell errors
  •  Misspell errors
 /*This file is used to demonstrate some error prone function in C.
 *Taken from the "Wirting Solid Code"
 */
#include <stdio.h>
int main()
{
     char ch;
     int word;
     short bHigh=4, bLow=1;
     char* pb=NULL;
     /*Two possible errors here
      * a). char can be unsigned even if x86 always uses signed char
      *     gcc can also change the behavior using -funsigned-char flag
      * b). the != has higher precedence than =, so this is equal to
      *     ch=(getchar() != EOF)
     if (ch=getchar() != EOF)
     {
          printf("Not real char: %c\n", ch);
     }



     /* Similar error:
      * It is bHigh<<(8+bLow);
      */
     word=bHigh<<8 + bLow;

     /* compiler warnning:
      * comparison is always false due to limited range of data type
      */
     ch=0xFF;
     if (ch==0xFF)
            printf("Happy\n");

     /* condition error
      * a). 063: octal number
      * b). & instead of && : compiler warnning: comparison is always true due to limited range of data type
      * c). /* comment, should use / *
      */
     if (word==063
         || (pb!=NULL & *pb !=0xFF )
//         || word=bHigh/*bLow
     )
     {
             printf("Condition matched\n");
     }

}
~                         
  •  Make assumption that long is 4 always bytes. how about 64 bit machine?
  • realloc() too flexible interface
  • getchar() handle the errors and results in the same return value
  • step through code use debugger (data flow)
  • use the size instead of pointer to control your loop (overflow....)
  • the risk to modify static variables in a function
        a). You have to make sure nobody  will call directly/indirectly that function before
        b). multiple threads
        c). volatile
  • the risk to refer the memory just released:
         a). internal memory manager may use that for free chain private information
         b). other thread may used it.
  • Compiler will help you to optimize for such code (high risk no return):

         size >> 2 instead of size/4
  • --size : error prone
         while (--size >= 0) //how about unsigned int size? or signed size is MIN_INT
  • ANSI type range:
          char                         0-----------------------------127
          signed char             -127(not -128)-----------127
          unsigned char         0-----------------------------255
          short                        -32767(not -32768)-----32767
          int                            -32767(not -32768)-----32767
          long                          -2147483647------------- 2147483647

         

No comments: