A Typical Error in C

 [Previous Chapter]  [Previous Page]  [Contents]  [Next Page]

buggyd.c
char * fetchname (FILE * in) {
   char name[128]; /* to be overrun */
   char * namep = name;
   int ch;
   while ((ch = getc(in)) != EOF) {
      *namep++ = ch;
   }
   *namep++ = '\0';
   return strdup(name);
}

*This is a widespread technique in C: Some input of unknown length is stored into a buffer of limited size (which might be quite large). Afterwards, the buffer contents is copied to a buffer of the necessary size by strdup.
 
*Secure alternatives which allow strings of arbitrary lengths to be read are not supported up to today by the C standard libraries.
 
*If the size of the input exceeds that of the buffer, ``some'' memory areas will be overwritten.
 
*Many C programmers believe until today that the worst thing to be expected in such a case is a crash of their program.
 
*Unfortunately, many of them don't know the layout of a stack frame...
 

 [Previous Chapter]  [Previous Page]  [Contents]  [Next Page]
Copyright © 2001, 2002 Andreas Borchert, converted to HTML on April 07, 2002