...
Do not reenter a function during the initialization of a static variable declaration. If a function is reentered during the constant initialization of a static object inside that function, the behavior of the program is undefined. Infinite recursion is not required to trigger undefined behavior, the function need only recur once as part of the initialization.
Noncompliant Code Example
This noncompliant example attempts to implement an efficient factorial function using caching. Since the initialization of the static local array cache
involves recursion, the behavior of the function is undefined, even though the recursion is not infinite.
...
Code Block |
---|
terminate called after throwing an instance of '__gnu_cxx::recursive_init_error' what(): std::exception |
Compliant Solution
This compliant solution avoids initializing the static local array cache
and instead relies on zero-initialization to determine whether each member of the array has been assigned a value yet, and if not, recursively computes its value. It then returns the cached value when possible, or computes the value as needed.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdexcept> int fact(int i) noexcept(false) { if (i < 0) { // Negative factorials are undefined. throw std::domain_error("i must be >= 0"); } // Use the lazy-initialized cache. static int cache[17]; if (i < (sizeof(cache) / sizeof(int))) { if(0 == cache[i]) { cache[i] = i > 0 ? i * fact(i - 1) : 1; } return cache[i]; } return i > 0 ? i * fact(i - 1) : 1; } |
Risk Assessment
Recursively reentering a function during the initialization of one of its static objects can result in an attacker being able to cause a crash or denial of service.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL38-CPP | Low | Unlikely | Medium | P2 | 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
Bibliography
[ISO/IEC 14882-2014] | 6.7, "Declaration Statement" |
...