...
Code Block |
---|
|
auto g() {
int i = 12;
return [=] () mutable {
i = 100;
return i;
};
}
void f() {
int i = g()();
} |
Noncompliant Code Example
In this noncompliant code example, a lambda reference captures a local variable from an outer lambda. However, this inner lambda outlives the lifetime of the outer lambda and any automatic local variables it defines, resulting in undefined behavior when an inner lambda object is executed within f()
.
Code Block |
---|
|
auto g(int val) {
auto outer = [val] {
int i = val;
auto inner = [&] {
i += 30;
return i;
};
return inner;
};
return outer();
}
void f() {
auto fn = g(12);
int i = fn();
} |
Compliant Solution
In this compliant solution, the inner lambda captures i
by copy instead of by reference:
Code Block |
---|
|
auto g(int val) {
auto outer = [val] {
int i = val;
auto inner = [i] {
return i + 30;
};
return inner;
};
return outer();
}
void f() {
auto fn = g(12);
int i = fn();
} |
Risk Assessment
Referencing an object outside of its lifetime can result in an attacker being able to run arbitrary code.
...