According to C99, if the fgets() function fails, the contents of its parameterized array are undefined. Therefore, reset the string to a known value to avoid possible errors on subsequent string manipulation functions.
In this example, an error flag is set upon fgets() failure. However, buf is not reset, and will have unknown contents.
char buf[1024];
FILE *fptr;
/* fptr initialized to some file */
if(fgets(buf, 1024, fptr) == NULL) {
/* set error flag and continue */
}
printf("Read in: %s\n", buf);
|
After fgets fails, buf is set to an error message.
char buf[1024];
FILE *fptr;
/* fptr initialized to some file */
if(fgets(buf, 1024, fptr) == NULL) {
/* set error flag and continue */
strcpy(buf, "fgets failed");
}
printf("Read in: %s\n", buf);
|
Making assumptions about the contents of the array set by fgets on failure could lead to undefined behavior, possibly resulting in abnormal program termination.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
FIO40-C |
1 (low) |
1 (low) |
2 (medium) |
P2 |
L3 |
\[[ISO/IEC 9899-1999:TC2|AA. C References#ISO/IEC 9899-1999TC2]\] Section 7.19.7.2, "The {{fgets}} function" |