Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm learning C++ lambda function. Why does it have this output?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading