Versions Compared

Key

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

...

Code Block
bgColor#FFCCCC
langcpp
auto g() {
  int i = 12;
  return [&] {
    i = 100;
    return i;
  };
}

void f() {
  int i = g()();
}

Compliant Solution

In this compliant solution, the lambda does not capture i by reference but instead captures it by copy. Consequently, the lambda contains an implicit nonstatic data member whose lifetime is that of the lambda.

Code Block
bgColor#ccccff
langcpp
auto g() {
  int i = 12;
  return [=] () mutable {
    i = 100;
    return i;
  };
}

void f() {
  int i = g()();
}

Risk Assessment

Referencing an object outside of its lifetime can result in an attacker being able to run arbitrary code.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP61-CPP

High

Probable

High

P6

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]Subclause 3.8, "Object Lifetime"
Subclause 5.1.2, "Lambda Expressions" 

...