Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added code comments

...

Code Block
bgColor#FFCCCC
langc
#include <stdio.h>
#include <string.h>
 
void func(void) {
  char buf[BUFSIZ];

  if (fgets(buf, sizeof(buf), stdin) == NULL) {
    /* Handle error */
  }
  buf[strlen(buf) - 1] = '\0'; /* discard newline */
}

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() happens to be a null character. This may occur, for example, if a binary data file is read by the fgets() call [Lai 2006]. If the first character in buf is a null character, strlen(buf) returns 0 and a write-outside-array-bounds error occurs.

...

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <string.h>
 
void func(void) {
  char buf[BUFSIZ];
  char *p;

  if (fgets(buf, sizeof(buf), stdin)) {
    p = strchr(buf, '\n');
    if (p) {
      *p = '\0';  /* discard newline */
    }
  } else {
    /* Handle error */
  }
}

...