Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory address of local variable changes depending on the presense of lambda parameters

Tags:

c++

I have the following code I was playing with. I have a local variable p and I have a lambda that prints out its address:

int main()
{
    int p = 0;
    auto lambda = [&p] {
        std::cout << &p << std::endl;
    };

    lambda(); // 0x7fff78e6b7e0
}

The address of the variable is the same no matter how many times I run the code. But I find that when I change the lambda definition to this:

auto lambda = [&p]() {
//                ^^

Meaning when I add an empty parameter list, I get a new address:

lambda(); // 0x7fff2291a260

You can test it out over here. Why does this happen? I'm running my code on both g++-4.8 and clang++ on Windows.

like image 441
David G Avatar asked Dec 28 '25 01:12

David G


1 Answers

The address change is absolutely ok. Compiler may generate different code for your lambdas. OS may load your program at different base address.

You can ensure that the variable address is the same no matter was parameter list specified or not:

#include <iostream>

int main()
{
    int p = 0;
    auto lambda1 = [&p] {
        std::cout << &p << std::endl;
    };

    auto lambda2 = [&p] (){
        std::cout << &p << std::endl;
    };

    lambda1(); //0x7fffe3034fb4
    lambda2(); //0x7fffe3034fb4
}
like image 139
Ivan Grynko Avatar answered Dec 30 '25 15:12

Ivan Grynko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!