1

How could the same memory location hold different values in the following program? I am using g++ compiler.

code:

#include<iostream>
using namespace std;

int main()
{
   const int i=100;
   int *j = const_cast<int*>(&i);
   *j=1;

   cout<<"The value of i is:"<<i<<endl;
   cout<<"The value j holds:"<<*j<<endl;
   cout<<"The address of i is:"<<&i<<endl;
   cout<<"The address of j is:"< <j<<endl;

}

output:

The value of i is:100
The value j holds:1
The address of i is:0xbffbe79c
The address of j is:0xbffbe79c
Inquisitive
  • 475
  • 1
  • 5
  • 13

2 Answers2

6

You've got undefined behavior, so anything can happen. In this case, the compiler knows that i cannot change value, and probably just uses the value directly.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • I'm no expert in undefined-behavior-omancy, but I feel like if you dereferenced its address, you'd get the modified value. – Wug Jun 24 '13 at 18:37
  • As I keep seeing mentioned over and over in "Secure Coding in C and C++", once you've invoked undefined behavior, the compiler is free to do anything it wants, including nothing at all. – Nathan Ernst Jun 24 '13 at 19:08
  • @Wug _If_ you dereference an address, you will get the value at that address. But in this case, the compiler is free to assume that the value of `i` never changes. Since it knows the value can only be `100`, it just uses the constant `100`. Another possibility is that the compiler put the variable `i` in read only memory, and `*j = 1;` causes the program to crash. One of the points of "undefined behavior" is that the compiler is free to assume that it doesn't occur, and optimize in consequence. – James Kanze Jun 25 '13 at 08:41
4

The memory cannot hold different values at the same time. But, modifying an object that was declared const is undefined-behavior so anything can happen.

Anything includes making it look like the same memory location is holding different values at the same time. What happens is that since i cannot be changed, it is a candidate for constant folding, so there isn't any memory involved when i appears in an expression.

K-ballo
  • 80,396
  • 20
  • 159
  • 169