#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.