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

Unexpected Pointer Behavior in C++: Why does variable point to a local variable's value when another pointer assignment is commented out?

I wrote this code:

#include <iostream>


int main()
{
    int x = 0;
    int *u, *k;
    
    {   
        int y = 9;
        u = &y;
    }
    
    int z = 11;
    k = &z;
    
    std::cout << "u = " << u << std::endl;
    std::cout << "k = " << k << std::endl;
    std::cout << "*u = " << *u << std::endl;
    std::cout << "*k = " << *k;

    return 0;
}

and as expected I received the output:

u = 0x7fff039b1440
k = 0x7fff039b1440
*u = 11
*k = 11

but by commenting out the line //k = &z; the output became like this:

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

u = 0x7ffebca2bc1c
k = 0
*u = 9

why does u point to the value 9 if the variable z should be located at this address?

>Solution :

as expected I received the output: […]

You have no valid justification for any particular expectation because your program has undefined behavior.

Here:

    {   
        int y = 9;
        u = &y;
    }

u is assigned the address of a variable whose lifetime ends when execution of the { ... } compound statement terminates. At that point, the value stored in u becomes indeterminate. Because you later read the (indeterminate) value of u, the behavior (of the whole execution of the whole program) is undefined.

That a different program (that also has undefined behavior) produces different output is not significant, no matter how closely related the programs’ sources are.

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