Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example , and the subsequent compliant solutions , are assumed to eventually call std::terminate() in accordance with the ERR50-CPP-EX1 exception described in ERR50-CPP. Do not abruptly terminate the program. Indicating the nature of the problem to the operator is elided for brevity.

...

In this compliant solution, std::fstream::close() is called before std::terminate() is called, ensuring that the file resources are properly closed:.

Code Block
bgColor#ccccff
langcpp
#include <exception>
#include <fstream>
#include <string>

void f(const std::string &fileName) {
  std::fstream file(fileName);
  if (!file.is_open()) {
    // Handle error
    return;
  }
  // ...
  file.close();
  if (file.fail()) {
    // Handle error
  }
  std::terminate();
}

...

In this compliant solution, the stream is implicitly closed through RAII before std::terminate() is called, ensuring that the file resources are properly closed:.

Code Block
bgColor#ccccff
langcpp
#include <exception>
#include <fstream>
#include <string>

void f(const std::string &fileName) {
  {
    std::fstream file(fileName);
    if (!file.is_open()) {
      // Handle error
      return;
    }
  } // file is closed properly here when it is destroyed
  std::terminate();
}

...

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

FIO51-CPP

Medium

Unlikely

Medium

P4

L3

Automated Detection

Tool

Version

Checker

Description

CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

ALLOC.LEAK

Leak
Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

DF4786, DF4787, DF4788


Klocwork
Include Page
Klocwork_V
Klocwork_V
RH.LEAK
Parasoft C/C++test
9.5BD-RES-LEAKS 
Include Page
Parasoft_V
Parasoft_V
CERT_CPP-FIO51-a
Ensure resources are freed
Parasoft Insure++
  


Runtime detection
Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C++: FIO51-CPPChecks for resource leak (rule partially covered)
Runtime detection

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

...

This rule supplements FIO42-C. Close files when they are no longer needed.

 

Bibliography

[ISO/IEC 14882-2014]Subclause 27.9.1, "File Streams"

...


...

Image Modified Image Modified Image Modified