Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

c - 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 
", local);

     *ptr = 100;

     printf("Modified value of local: %d 
", local);

     return 0;
}

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

$ ./volatile

Initial value of local : 10

Modified value of local: 100

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...