I wrote a few lines of code to fool around with pointers to stack variables. The idea initially was very simple but then I stumbled upon a weird behavior...
Here is what I wanted to do:
- open a scope,
- declare and initialize an int,
- store its address in a global variable and close the scope,
and then
- open a new scope,
- declare an int and initialize its value using the previous pointer.
As expected, the int in the second scope retains the value of the first int but when it comes to altering it through the global pointer (initialized in 3) then its value does not change, although the global pointer does hold the correct address!
I pasted the code and output below.
NB : Yes, its playful and I wouldn't use this hack in real-life code.... I just wish to gain a deeper understanding of what's going on at machine code level.
void main()
{
int * p, * q;
{
int x = 11;
p = &x;
// Obvious check
cout << "@x= " << &x << endl;
cout << "p= " << p << endl;
cout << "x= " << x << endl;
cout << endl;
}
{
int y;
// Trying to alter y through previous x's address
*p = 666;
cout << "*p= " << *p << endl;
cout << "y= " << y << endl;
cout << endl;
// Trying to alter y through y's address
q = &y;
*q = 123;
cout << "@y= " << &y << endl;
cout << "q= " << q << endl;
cout << "y= " << y << endl;
cout << endl;
}
cout << (p==q ? "same" : "different!") << endl;
}
Now the output:
@x= 0015FCEC
p= 0015FCEC
x= 11 ============> everything is going as planned :-)
*p= 666 ============> the int pointed by p did change ...
y= 11 ============> ... but y still holds the previous x's value.
@y= 0015FCEC
q= 0015FCEC ============> And yet p and q point to the same int!
y= 123
different! ============> Interestingly, p==q returns false.