Versions Compared

Key

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

...

For more information on exception specifications of destructors, see DCL58-CPP. Destructors and deallocation functions must be declared noexcept.

Noncompliant Code Example

In this noncompliant example, the constructor of global may throw an exception during program startup (the std::string constructor accepting a const char * and a default allocator object is not marked noexcept(true) and thus allows all exceptions). This exception is not caught by the function-try-block on main(), resulting in a call to std::terminate() and abnormal program termination.

Code Block
bgColor#FFcccc
#include <string>
 
static const std::string global("...");

int main()
try {
  // ...
} catch(...) {
  // IMPORTANT: will not catch exceptions thrown
  // from the constructor of global.
}

Compliant Solution

Compliant code must prevent exceptions from escaping during program startup and termination. This compliant solution avoids defining a std::string at global namespace scope, and instead uses a static const char *:

Code Block
bgColor#ccccff
static const char *global = "...";

int main() {
  // ...
}

Risk Assessment

Throwing an exception which cannot be caught results in abnormal program termination, and can lead to denial-of-service attacks.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ERR41-CPP

Low

Likely

Low

P9

L2

Automated Detection

Tool

Version

Checker

Description

    

Related Vulnerabilities

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

Related Guidelines

 

Bibliography

[ISO/IEC 14882-2014]15.4, "Exception Specifications"
[Sutter 00]Item 8, "Writing Exception-Safe Code—Part 1"