A call to the fopen() or freopen() function must be matched with a call to fclose() before the lifetime of the last pointer object that stores the return value of the call has ended.
Standard FILE objects and their underlying representation (file descriptors on POSIX platforms or handles elsewhere) are a finite resource that must be carefully managed. The number of files that an implementation guarantees may be open simultaneously is bounded by the FOPEN_MAX macro defined in <stdio.h>. The value of the macro is guaranteed to be at least 8. Consequently, portable programs must either avoid keeping more than FOPEN_MAX files at the same time or be prepared for functions such as fopen() to fail due to resource exhaustion.
...
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 148153.) 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()).
...
Failing to properly close files may allow unintended access to, or exhaustion of, system resources.
Rule | Severity | Likelihood | Detectable |
|---|
Repairable | Priority | Level | |
|---|---|---|---|
FIO22-C | Medium | Unlikely | No |
No |
P2 | L3 |
Automated Detection
Tool | Version | Checker | Description |
|---|---|---|---|
| Compass/ROSE |
5.0
| Klocwork |
| RH.LEAK |
| LDRA tool suite |
| 49 D |
| Partially implemented | |||||||||
| Parasoft C/C++test |
| CERT_C-FIO22-a | Ensure resources are freed |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
| CERT C Secure Coding Standard | WIN03-C. Understand HANDLE inheritance |
| SEI CERT C++ |
| Coding Standard |
| FIO51-CPP. |
| Close files |
| when they are no longer needed | |
| CERT Oracle Secure Coding Standard for Java | FIO04-J. Release resources when they are no longer needed |
| MITRE CWE | CWE-403, UNIX file descriptor leak CWE-404, Improper resource shutdown or release CWE-770, Allocation of resources without limits or throttling |
Bibliography
| [Dowd 2006] | Chapter 10, "UNIX Processes" ("File Descriptor Leaks," pp. 582–587) |
| [IEEE Std 1003.1:2013] | XSH, System Interfaces, open |
| [MSDN] | Inheritance (Windows) |
| [NAI 1998] |
...