Possible Duplicate:
Modified a constant in c
const int z = 420;
const void *v;
v = &z;
printf("\n%d | %d",z,*(int *)v);
//420 | 420
printf("\n%d | %d",*(char *)&z,*(char *)v); //0th-Bit same value
//-92 | -92
printf("\n%d | %d",*((char *)&z+1),*((char *)v+1) ); //1st-Bit same value
//1 | 1
/***********************************************/
*((char *)&z+1) = 21; //I change value for the 1st-Bit
//see v is not touched here.
printf("\n%d | %d -(note)-successfully corrupted (z+1) and change reflected in (v+1)",*((char *)&z+1),*((char *)v+1) );
//21 | 21
//yes change is reflected in v after corruption of z
/****************the problem******************/
printf("\n%d | %d",z,*(int *)v); //but now value of v is courrupt...while that of z is same
//420 | 5540
printf("\n%u | %u",&z,v); //same address different values?
//1310548 | 1310548
/*************additional info*******************/
printf("\n%d | %d",*(&(*(&z+1))-1),*(int *)v);
//5540 | 5540
printf("\n%u | %u",(&(*(&z+1))-1),v);
//1310548 | 1310548
1>
void pointer pointing to “z”
when dereferenced gives corrupted value
but when z is used directly it gives original value.
so same address is holding 2 different values
2>
when z is subjected to an identity pointer transformation
(i.e. increment and decrement back)
z will now output the corrupted value!
but z when subjected to normal or no transformations
like “*(&z)” will still give the original value.
Stop asking this question 😉
If it helps, you can assume that the compiler has taken code like this:
And replaced it with:
That’s not guaranteed, you can’t rely on it, but it’s the kind of thing compilers do, and it would account for what you’re seeing.
You also take the address of
z, but the compiler won’t/can’t necessarily track the use of that pointer, and replace all accesses through it in the same way. That’s a much harder job than just recognising that the symbolzrefers to a const object. So when you invalidly modified that const object, one of the ways in which undefined behavior has manifested is the inconsistencies you’re seeing.If you want to know what your compiler has actually done, and you won’t follow James’ advice, then you’re out of luck. Nobody here knows for sure exactly what your compiler has done. Nobody even knows what compiler you’re using. Different compilers do different things.