Last time I asked how can I generate segmentation
fault in a program by bypassing the compiler’s promise of not overwriting the const
memory. User Marco Bonelli described the following way, which worked perfectly.
JavaScript
x
11
11
1
const static int global = 123;
2
3
int main(void) {
4
int *ptr = (int *)&global;
5
*ptr = 456;
6
7
// or, equivalent
8
const int *ptr2 = &global;
9
*(int *)ptr2 = 456;
10
}
11
Either way I was able to generate segmentation fault.
-
JavaScript131
int *ptr = (int *)&global;
2*ptr = 456;
3
-
JavaScript131
const int *ptr2 = &global;
2*(int *)ptr2 = 456;
3
Now my question is what is it that is preventing the pointer from writing to a global const
block of memory but not to the local const
block of memory. For example, in the below code I was able to write to the const
block of memory without any issue.
JavaScript
1
19
19
1
#include <stdio.h>
2
3
int main(void) {
4
const int local = 123;
5
6
int *ptr = (int *)&local;
7
*ptr = 456;
8
9
// how come this be possible?
10
printf("%dn", local); // -> 456
11
12
// or, equivalent
13
const int *ptr2 = &local;
14
*(int *)ptr2 = 512;
15
16
// how come this be possible?
17
printf("%dn", local); // -> 512
18
}
19
I’m curious about knowing how this happened. Please enlighten me.
If it matters, I’m using gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
.