According to C99 [[ISO/IEC 9899:1999]], if the fgets() function fails, the contents of the array it was writing to are undefined. As a result it is necessary to reset the string to a known value to avoid possible errors on subsequent string manipulation functions.
Non-Compliant Code Example
In this example, an error flag is set upon fgets() failure.
char buf[BUFSIZ];
FILE *file;
/* Initialize file */
if (fgets(buf, sizeof(buf), file) == NULL) {
/* set error flag and continue */
}
However, buf is not reset, and will have unknown contents.
Compliant Solution
In this compliant solution, buf is set to an empty string if fgets fails.
char buf[BUFSIZ];
FILE *file;
/* Initialize file */
if (fgets(buf, sizeof(buf), file) == NULL) {
/* set error flag and continue */
*buf = '\0';
}
Risk Assessment
Making invalid assumptions about the contents of an array modified by fgets() can result in undefined behavior and abnormal program termination.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
FIO40-C |
low |
probable |
medium |
P4 |
L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[ISO/IEC 9899:1999]] Section 7.19.7.2, "The fgets function"
09. Input Output (FIO) FIO41-C. Do not call getc() or putc() with stream arguments that have side effects