0

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:

  1. open a scope,
  2. declare and initialize an int,
  3. store its address in a global variable and close the scope,

and then

  1. open a new scope,
  2. 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.
kenz
  • 112
  • 12
MaBu38
  • 1
  • 1
  • 1
    Everything after "and then" is undefined behavior. – Sergey Kalinichenko Aug 13 '15 at 10:44
  • Well yes, I do understand that.My question really was about the hidden data associated to a pointer, as it turns out that the "address" held by a pointer is completed by other information within the compiled executable (hence the operator== failure). – MaBu38 Aug 13 '15 at 13:25

0 Answers0