Using the value of a pointer to a FILE object after the associated file is closed is undefined behavior. (See undefined behavior 148.) Programs that close the standard streams (especially stdout but also stderr and stdin) must be careful not to use these streams in subsequent function calls, particularly those that implicitly operate on them (such as printf(), perror(), and getc()).
This rule can be generalized to other file representations.
In this noncompliant code example, the stdout stream is used after it is closed:
#include <stdio.h>
int close_stdout(void) {
if (fclose(stdout) == EOF) {
return -1;
}
printf("stdout successfully closed.\n");
return 0;
} |
In this compliant solution, stdout is not used again after it is closed. This must remain true for the remainder of the program, or stdout must be assigned the address of an open file object.
#include <stdio.h>
int close_stdout(void) {
if (fclose(stdout) == EOF) {
return -1;
}
fputs("stdout successfully closed.", stderr);
return 0;
} |
Using the value of a pointer to a FILE object after the associated file is closed is undefined behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
FIO46-C | Medium | Unlikely | Medium | P4 | L3 |
Tool | Version | Checker | Description |
|---|---|---|---|
| CodeSonar | IO.UAC | Use after close | |
5.0 | Can detect violations of this rule with CERT C Rule Pack | ||
RH.LEAK | |||
48 D | Partially implemented | ||
| Parasoft C/C++test | 9.5 | BD-RES-FREE | |
| Polyspace Bug Finder | R2016a | Function closes a previously closed stream Argument to a standard function does not meet requirements for use in the function Function operates on a previously closed stream |
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
| [IEEE Std 1003.1:2013] | XSH, System Interfaces, open |
| [ISO/IEC 9899:2011] | Subclause 7.21.3, "Files" |