Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion regarding modification of const variable using pointers

Following example added confusion in my understanding. I'm unable to understand how is it possible to modify the const variable local. Please help me to understand the same.

 /* 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

Initial value of local : 10

Modified value of local: 100

like image 761
codey modey Avatar asked Jan 27 '14 03:01

codey modey


1 Answers

This is simply undefined behavior if we look at the C99 draft standard section 6.7.3 Type qualifiers paragraph 4 it says:

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined. If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.115)

So you can not have any expectations on the results and you should not be doing this.

If we look at paragraph 2 it says:

The properties associated with qualified types are meaningful only for expressions that are lvalues.114)

and footnote 114 says:

The implementation may place a const object that is not volatile in a read-only region of storage. Moreover, the implementation need not allocate storage for such an object if its address is never used.

In general the implementation does not have to make const variables read-only but it may but as R.. points out placing an automatic variable in read-only memory would be hard.

like image 150
Shafik Yaghmour Avatar answered Sep 20 '22 13:09

Shafik Yaghmour