Are you sure that it is in .rodata
? This code
const int temp = 10;
int main(void) {
int *ptr = &temp;
*ptr = 100;
}
does crash on Linux, GCC 5.2.1; nm
shows the symbol temp
existing in .rodata
.
However,
int main() {
const int temp = 10;
int *ptr = &temp;
*ptr = 100;
}
does not crash, because the variable has automatic storage duration and it is allocated on stack instead of it residing in read-only pages of .rodata
section.
Also C11 draft n1570, 6.7.3 paragraph 6:
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. [...]
And of course undefined behaviour means:
behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements
So indeed anything can happen, and even though your program does not crash on this, it is still wrong.
In any case, you got the warning. Whenever a C compiler gives a warning, you as a programmer should take it as an error (even by explicitly setting the -Werror
) because they really are; only there is lots of old code which relies upon certain bad behaviour that these things that really actually are errors, cannot be made true errors.
Note that the C standard does not say that the int *ptr = &temp;
is wrong - it is perfectly valid C as such, and only whenever you attempt to change temp
via this ptr
the undefined behaviour occur.