...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h> #include <string.h> void func(void) { char buf[BUFSIZ + 1]; if (fgets(buf, sizeof(buf), stdin)) { if (*buf) { /* see FIO37-C */ buf[strlen(buf) - 1] = '\0'; } } else { /* Handle error condition */ } } |
However, if the last character in buf is not a newline, this code overwrites an otherwise valid character.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h> #include <string.h> void func(void) { char buf[BUFSIZ + 1]; char *p; if (fgets(buf, sizeof(buf), stdin)) { p = strchr(buf, '\n'); if (p) { *p = '\0'; } } else { /* Handle error condition */ } } |
An obvious alternative is to leave room in the buffer for one more character, and when no newline is transferred, append a newline followed by a null-termination character. This approach is unsafe because it quietly accepts an input that is not what was actually intended, with unknown consequences.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...