const int z = 420;
printf("\n%d | %d",z ,*(&(*(&z+1))-1) );
// O/P:420 | 420
printf("\n%u | %u",&z,(&(*(&z+1))-1) ); //address
// O/P:1310548 | 1310548
*((char *)&z+1) = 21; //I change value for the 1st-Bit
//corrupting constant
printf("\n%d | %d",z ,*(&(*(&z+1))-1) );
//the complex(not really) expression evaluates to z
// O/P:420| 5540
printf("\n%u | %u",&z ,(&(*(&z+1))-1) );
//the complex(not really) expression evaluates to &z
// O/P:1310548 | 1310548
Why is this happening?
it seems that I have successfully modified constant in C
by modify I mean I have changed the bits in the constants address range
as the “complex(not really) unity/identity expression”
changes value after corruption.
but the z remains same. Why?
how come same address have different values when de-referenced. ?
PS: u can use any identity expression
eg.printf("%d",*(int*)((char*)&(*((char*)&z+1))-1));
[edit]
ok let me re-phrase it:
z = 420
&z = 1310548
*(&(*(&z+1))-1) = 420
(&(*(&z+1))-1) = 1310548
now I do to corrupt the constant
*((char *)&z+1) = 21;
NOW AFTER CORRUPTING:
z = 420 // NO CHANGE EVEN THOUGH I have corrupted
&z = 1310548
*(&(*(&z+1))-1) = z = 5540 // THE CHANGE
(&(*(&z+1))-1) = &z = 1310548
WHY?
There’s not a while lot of mystery here. By using casts to tell the compiler that what you’re changing isn’t
constqualified, you’re causing undefined behavior:6.7.3/5 “Type qualifiers” (C99):
Some implementations might have placed the variable
zin read only memory and you’d either get no apparent change or some sort of access violation.In any case, undefined behavior means all bets are off – in your case you’re able to see the apparent modification of a
constvalue.