If the C fgets()
function fails, the contents of the array it was writing to are indeterminate. (See also undefined behavior 170 in Annex J of the C Standard.) Consequently, it is necessary to reset the string to a known value to avoid possible errors on subsequent string manipulation functions.
The fgetws()
function is similarly affected.
In this noncompliant code example, an error flag is set upon fgets()
failure:
#include <stdio.h> void func(FILE *file) { char buf[BUFSIZ]; if (fgets(buf, sizeof(buf), file) == NULL) { /* Set error flag and continue */ } } |
However, buf
is not reset and has unknown contents.
In this compliant solution, buf
is set to an empty string if fgets()
fails. The equivalent solution for fgetws()
would set buf
to an empty wide string:
#include <stdio.h> void func(FILE *file) { char buf[BUFSIZ]; if (fgets(buf, sizeof(buf), file) == NULL) { /* Set error flag and continue */ *buf = '\0'; } } |
FIO40-EX0: If the string goes out of scope immediately following the call to fgets()
or fgetws()
or is not referenced in the case of a failure, it need not be reset.
Making invalid assumptions about the contents of an array modified by fgets()
or fgetws()
can result in undefined behavior and abnormal program termination.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FIO40-C | Low | Probable | Medium | P4 | L3 |
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
CERT C++ Secure Coding Standard | FIO40-CPP. Reset strings on fgets() failure |