Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: New CS and some weasel words

...

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

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

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 call std::terminate(), std::abort(), or std::_Exit(). Indicating the nature of the problem to the operator is elided for brevity.

Compliant Solution

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();
}

Compliant Solution

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();
}

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.

...