Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFCCCC
char buf[BUFSIZ + 1];

if (fgets(buf, sizeof(buf), fp) == NULL) {
  /* handle error */
}
buf[strlen(buf) - 1] = '\0';

Wiki Markup
The {{strlen()}} function computes the length of a string by determining the number of characters that precede the terminating null character.   A problem occurs if the first character read from the input by {{fgets()}} is a null character.  This may occur, for example, if a binary data file is read by the {{fgets()}} call \[[Lai 06|AA. C References#Lai 06]\].  If the first character in {{buf}} is a null character, {{strlen(buf)}} will return 0 and a write-outside-array-bounds error will occur.  

Compliant Solution

This compliant solution uses strchr() to replace the newline character in the string, if it exists (see FIO36-C. Do not assume a newline character is read when using fgets()).

...