...
Page properties | ||
---|---|---|
| ||
We may want an overarching rule that covers any situation where destructors are not automatically called, since there can be all sorts of nasty things that happen in those situations. |
Noncompliant Code Example
In this noncompliant code example, a std::fstream
object f
is constructed. The constructor for std::fstream
calls std::basic_filebuf<T>::open()
, and the default std::terminate_handler
called by std::terminate()
is std::abort()
, which does not call destructors. Thus, the underlying std::basic_filebuf<T>
object maintained by the object is not properly closed, and the program has no way of determining if an error occurs while flushing or closing the file.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <exception> #include <fstream> #include <string> void f(const std::string &N) { std::fstream f(N); if (!f.is_open()) { // Handle error return; } // ... std::terminate(); } |
Compliant Solution
In this compliant solution, std::fstream::close()
is called prior to calling std::terminate()
, ensuring that the file resources are properly closed.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <exception> #include <fstream> #include <string> void f(const std::string &N) { std::fstream f(N); if (!f.is_open()) { // Handle error return; } // ... f.close(); if (f.fail()) { // Handle error } std::terminate(); } |
Risk Assessment
Failing to properly close files may allow an attacker to exhaust system resources and can increase the risk that data written into in-memory file buffers will not be flushed in the event of abnormal program termination.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FIO42-CPP | Medium | Unlikely | Medium | P4 | L3 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Coding Standard | MEM51-CPP. Properly deallocate dynamically allocated resources |
CERT C Coding Standard | FIO42-C. Close files when they are no longer needed |
Bibliography
[ISO/IEC 14882-2014] | 27.9.1, "File Streams" |
...