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 | ||
|---|---|---|
| ||
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.
...