CERT-FIO40-C
In this section:
Synopsis
Reset strings on fgets() or fgetws() failure.
Enabled by default
Yes
Severity/Certainty
Low/Medium

Full description
If either of the C Standard fgets() or fgetws() functions fail, the contents of the array being written is indeterminate. (See undefined behavior 170.) It is necessary to reset the string to a known value to avoid errors on subsequent string manipulation functions.
Coding standards
- CERT FIO40-C
Reset strings on fgets() failure
Code examples
The following code example fails the check and will give a warning:
#include <stdio.h>
enum { BUFFER_SIZE = 1024 };
void func(FILE *file) {
char buf[BUFFER_SIZE];
if (fgets(buf, sizeof(buf), file) == NULL) {
/* Set error flag and continue */
}
char c = buf[0];
}
The following code example passes the check and will not give a warning about this issue:
#include <stdio.h>
enum { BUFFER_SIZE = 1024 };
void func(FILE *file) {
char buf[BUFFER_SIZE];
if (fgets(buf, sizeof(buf), file) == NULL) {
/* Set error flag and continue */
*buf = '\0';
}
}