Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added mention of fgetws()

The fgets() function is typically used to read a newline-terminated line of input from a stream. The fgets() function takes a size parameter for the destination buffer and copies, at most, size-1 characters from a stream to a string. Truncation errors can occur if the programmer assumes that the last character in the destination string is a newline.

The fgetws() function is similarly affected.

Non-Compliant Code Example

...

This compliant solution uses strchr() to replace the newline character in the string (if it exists). The equivalent solution for fgetws() would use wcschr().

Code Block
bgColor#ccccff
char buf[BUFSIZ + 1];
char *p;

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

...

Assuming a newline character is read by fgets() or fgetws() can result in data truncation.

...