Versions Compared

Key

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

...

In this example, an error flag is set upon fgets() failure. However, buf is not reset, and will have unknown contents.

Code Block
bgColor#ffcccc

enum { BUFFERSIZE = 1024 };

char buf[BUFFERSIZEBUFSIZ];
FILE *file;
/* Initialize file */

if (fgets(buf, sizeof(buf), file) == NULL) {
  /* set error flag and continue */
}
printf("Read in: %s\n", buf);

However, buf is not reset, and will have unknown contents.

Compliant Solution

In this compliant solution, buf is set to an empty string if fgets fails.

Code Block
bgColor#ccccff
enum { BUFFERSIZE = 1024 };

char buf[BUFFERSIZEBUFSIZ];
FILE *file;
/* Initialize file */

if (fgets(buf, sizeof(buf), file) == NULL) {
  /* set error flag and continue */
  *buf = '\0';
}
printf("Read in: %s\n", buf);

Risk Assessment

Making invalid assumptions about the contents of an array modified by fgets() can result in undefined behavior and abnormal program termination.

...