The behavior of a program is undefined when it uses the value of a pointer to a FILE
object after the associated file is closed (see undefined behavior 148.) Programs that close the standard streams (especially stdout
but also stderr
and stdin
) must be careful not to use the stream objects in subsequent function calls, particularly those that implicitly operate on such objects (such as printf()
, perror()
, and getc()
).
Noncompliant Code Example
In this noncompliant code example the printf()
function is called after the stdin
is closed.
#include <stdio.h> int close_stdin(void) { if (fclose(stdin) == 0) { return -1; } else { printf("stdin successfully closed.\n"); } return 0; }
Compliant Solution
In this compliant solution, stdin
is not used again after it is closed. This must remain true for the remainder of the program.
#include <stdio.h> int close_stdin(void) { if (fclose(stdin) == 0) { return -1; } else { fprintf(stderr, "stdin successfully closed.\n"); } return 0; }
Risk Assessment
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 |
---|---|---|---|---|---|
FIO42-C | Medium | Unlikely | Medium | P4 | L3 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
5.0 | Can detect violations of this rule with CERT C Rule Pack | ||
2024.4 | RH.LEAK | ||
9.7.1 | 49 D | Fully implemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard | FIO42-CPP. Ensure files are properly closed when they are no longer needed |
CERT Oracle Secure Coding Standard for Java | FIO04-J. Release resources when they are no longer needed |
ISO/IEC TS 17961 | Failing to close files or free dynamic memory when they are no longer needed [fileclose] |
MITRE CWE | CWE-404, Improper resource shutdown or release |
Bibliography
[IEEE Std 1003.1:2013] | XSH, System Interfaces, open |