Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two different values at the same memory address

Tags:

c++

Code

#include <iostream>
using namespace std;

int main() {
    const int N = 22;
    int * pN = const_cast<int*>(&N);
    *pN = 33;
    cout << N << '\t' << &N << endl;
    cout << *pN << '\t' << pN << endl;
}

Output

22 0x22ff74

33 0x22ff74

Why are there two different values at the same address?

like image 686
L.Lawliet Avatar asked Aug 29 '10 05:08

L.Lawliet


2 Answers

Why are there two different datas at the same address?

There aren't. The compiler is allowed to optimize any mention of a const to be as though you had written its compile-time value in there.

Note that the compiler is also allowed to generate code that erases your hard disk when you run it if you do nasty tricks like writing to memory reserved for consts.

like image 192
Eric Lippert Avatar answered Nov 15 '22 19:11

Eric Lippert


You get undefined behavior on the line *pN = 33;, because you're modifying a const value. Anything can happen. Don't do it.


Likely, though, your compiler simply optimized. In the line:

cout << N << '\t' << &N << endl;

It knows N is a constant expression with the value 22, so just changes the line to:

cout << 22 << '\t' << &N << endl;

And on your next line, you fetch the value at the address of N, which you "set" to 33. (But really, all you did was remove any guarantees about the state of your program.)

like image 28
GManNickG Avatar answered Nov 15 '22 21:11

GManNickG