MiddleDebuggingVery commonNot answered yet
Why does this returned lambda read freed memory?
This factory returns a counter, but calling the result gives garbage or crashes.
std::function<int()> makeCounter() {
int count = 0;
return [&]() { return ++count; };
}
Find and fix the bug.
The lambda captures count by reference ([&]), but count is destroyed when makeCounter returns, so calling the returned std::function reads a dangling reference — UB. Fix: capture by value, [count]() mutable { return ++count; }.
- ✗Believing reference capture extends the captured variable's lifetime
- ✗Blaming std::function instead of the by-reference capture
- ✗Thinking adding mutable fixes what is actually a lifetime bug
- →When is capturing by reference in a lambda actually safe?
- →Why does a by-value capture need
mutableto be modified?