This is my code
#include<iostream>
int* p = nullptr;
auto fun()
{
int a = 1;
p = &a;
std::cout << &a << std::endl;
auto z = [&a]() {std::cout << &a << " "; a++; std::cout << "lambda call " << a << std::endl; };
return z;
}
int main()
{
auto z = fun();
std::cout << *p << "\n";
z();
z();
fun()();
}
and the output is
0x7fffd10af15c
1
0x7fffd10af15c lambda call 21880
0x7fffd10af15c lambda call 21880
0x7fffd10af15c
0x7fffd10af15c lambda call 21880
The version of my compiler is gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1)
Why do i have this output? Is it an undefined behavior?
>Solution :
Yes, the problem is that a is a local variable in the fun function and gets destroyed by the time fun finishes. That means, the returned lambda z is referencing an area on the stack where a used to be, but now when z is called this area is used for something else (this is why you see 21880).
In order to avoid this problem you need to prevent a being destroyed when leaving fun‘s scope. One way is to declare a as a global variable, just like p. The other one is to make it a static variable.