Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a variable at the same address producing 2 different values? [duplicate]

Consider this :

#include <iostream>
using namespace std;

int main(void)
{
    const int a1 = 40;
    const int* b1 = &a1;
    char* c1 = (char *)(b1);
    *c1 = 'A';
    int *t = (int*)c1;


    cout << a1 << " " << *t << endl;
    cout << &a1 << " " << t << endl; 

    return 0;
}

The output for this is :

40 65 
0xbfacbe8c 0xbfacbe8c

This almost seems impossible to me unless compiler is making optimizations. How ?

like image 520
shrinidhisondur Avatar asked Mar 26 '14 09:03

shrinidhisondur


1 Answers

This is undefined behavior, you are modifying a const variable so you can have no expectation as to the results. We can see this by going to the draft C++ standard section 7.1.6.1 The cv-qualifiers paragraph 4 which says:

[...]any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

and even provides an example:

const int* ciq = new const int (3); // initialized as required
int* iq = const_cast<int*>(ciq); // cast required
*iq = 4; // undefined: modifies a const object

In the standard definition of undefined behaviour in section 1.3.24, gives the following possible behaviors:

[...] Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). [...]

like image 144
Shafik Yaghmour Avatar answered Sep 21 '22 16:09

Shafik Yaghmour