...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <functional> void f() { auto l = [](const int &j) { return j; }; std::function<int(const int &)> fn(l); int i = 42; int j = fn(i); } |
Noncompliant Code Example
In this noncompliant code example, the constructor for the automatic variable s
is not called because execution does not flow through the declaration of the local variable due to the goto
statement. Because the constructor is not called, the lifetime for s
has not begun. Therefore, calling S::f()
uses the object outside of its lifetime and results in undefined behavior.
Code Block | ||||
---|---|---|---|---|
| ||||
class S {
int V;
public:
S() : V(12) {} // Not a trivial constructor
void f();
};
void f() {
// ...
goto bad_idea;
// ...
S s; // Control passes over the declaration, so initialization does not take place.
bad_idea:
s.f();
} |
Compliant Solution
This compliant solution ensures that s
is properly initialized prior to performing the local jump:
Code Block | ||||
---|---|---|---|---|
| ||||
class S {
int V;
public:
S() : V(12) {} // Not a trivial constructor
void f();
};
void f() {
S s;
// ...
goto bad_idea;
// ...
bad_idea:
s.f();
} |
Risk Assessment
Referencing an object outside of its lifetime can result in an attacker being able to run arbitrary code.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...