Confusion about modifying a constant variable with pointers

In the following example, confusion appeared in my understanding. I cannot figure out how to change the const local variable. Please help me understand the same thing.

/* Compile code without optimization option */ // volatile.c #include <stdio.h> int main(void) { const int local = 10; int *ptr = (int*) &local; printf("Initial value of local : %d \n", local); *ptr = 100; printf("Modified value of local: %d \n", local); return 0; } 

$ gcc volatile.c -o volatile -save-temps

$. / volatile

Original local value: 10

Modified local value: 100

+6
source share
2 answers

This is just undefined behavior if we look in the section of the standard C99 project 6.7.3 Type 4 indentation, which says:

If an attempt is made to modify an object defined using the const type using an lvalue with a non-constant qualified type, the behavior is undefined. If an attempt is made to refer to an object defined using an unstable type by using the lvalue value with a non-volatile type, the behavior is undefined. 115)

Thus, you cannot have any expectations about the results, and you should not do this.

If we look at paragraph 2, he says:

Properties associated with qualified types make sense only for expressions that are lvalues. 114)

and footnote 114 says:

An implementation may place a const object that is not mutable in a read-only area of ​​the storage location. Moreover, an implementation should not allocate storage for such an object if its address is never used.

In the general case, an implementation is not required to make read-only constant variables, but it can, but since R .. indicates that an automatic variable in read-only memory will be difficult.

+6
source

Perhaps because ptr points to int , not const int , so you can write to the memory address contained in ptr . In fact, there is nothing but this.

const does not actually indicate the memory location as read-only; whether it is really read-only or not is not defined by the language standard. This is usually not the case (as you found out.) But still you should not write on it.

-1
source

All Articles