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