#include <stdio.h>
int main() {
// case 1
const int a = 10;
int * ptr1 = &a;
*ptr1 = 11;
printf("%d\n",*ptr1);
// case 2
const static int b = 10;
static int * ptr2 = &b;
*ptr2 = 11;
printf("%d\n",*ptr2);
return 0;
}
In this program I can understand the case 1 (By assigning the address of the const variable to a non-constant pointer, We can change the variable value). if I apply the same concept to case 2 i won't work. It gives segmentation fault. What is the reason ? Is there is any other concept for case2 ? Here I am using gcc compiler.
By attempting to modify a const object through a non-const pointer, that triggers undefined behavior in your program.
This is spelled out in section 6.7.3p6 of the C standard:
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.
When you have undefined behavior in your program, there is no guarantee of what it will do. It might crash (as in your second case), it might give strange results, or it may appear to work properly (as in your first case).
So both cases have undefined behavior. They just happen to manifest differently.
In case 1, a has automatic storage duration. Automatic storage duration is most often implemented using the hardware stack, except when optimization keeps a value in a register or folds it into expressions. The stack cannot be read-only because it is used for many non-const things, so the C implementation is unable to enforce const for a.
In case 2, b has static storage duration, and it is put into an area of memory with other const objects. That memory is marked read-only (after it is initialized), which enforces the const property.
This behavior is specific to your C implementation and particular circumstances and may vary when circumstances change. It is not defined by the C standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With