CertC-FIO40¶
Reset strings on fgets() or fgetws() failure
Required inputs: IR
If either of the C Standard fgets() or fgetws() functions fail, the contents of the array being written is indeterminate . (See undefined behavior 175 .) It is necessary to reset the string to a known value to avoid errors on subsequent string manipulation functions.
Noncompliant Code Example
In this noncompliant code example, an error flag is set if fgets() fails. However, buf is not reset and has indeterminate contents:
#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 */
}
}
|
Compliant Solution
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>
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';
}
}
|
Exceptions
FIO40-C-EX1: 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.
Risk Assessment
Making invalid assumptions about the contents of an array modified by fgets() or fgetws() can result in undefined behavior 175 and abnormal program termination .
| Rule | Severity | Likelihood | Detectable | Repairable | Priority | Level |
|---|---|---|---|---|---|---|
| FIO40-C | Low | Probable | Yes | Yes | P6 | L2 |
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
reset_string_fgets_failure |
Reset strings on fgets() or fgetws() failure. |
None |
False |
Options
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
This rule has no individual options.