I know global const is stored in .rodata
Also, I know variables declared in functions are stored in the stack. However since const is supposed to be only read only, is there a special section in stack for them? how are accesses to them controlled?
I know global const is stored in .rodata
Also, I know variables declared in functions are stored in the stack. However since const is supposed to be only read only, is there a special section in stack for them? how are accesses to them controlled?
What you really should know: If an object is declared as const, the compiler will not easily let you attempt to modify it, and if you get around the compiler, then any attempt to modify the object is undefined behaviour. That's it. Nothing else. Forget about .rodata or anything you learned, what counts is that an attempt to modify a const object is undefined behaviour.
What I mean by "the compiler doesn't let you" and getting around it:
const int x = 5;
x = 6; // Not allowed by compiler
int* p = &x; *p = 6; // Not allowed by compiler
int* p = (int*)&x; *p = 6; // Allowed by compiler, undefined behaviour.
Executing the last statement can crash, or change x to 6, or change x to 999, or leave x unchanged, or make it behave in a schizophrenic way where it is 5 at some times and 6 at other times, including x == x being false.
The const
local variable may be not stored at all, when it's initialized with a constant epression. Consider following code:
int foo(int param)
{
const int value = 10;
return param + value;
}
It is likely that an optimizing compiler will generate assembly code with e.g. add
operation, where value
is substituted by 10
literal.
Other than that, many compilers would place them on the stack frame, just as for "ordinary" automatic variables, thus any protection you can get is by compiler itself.
No, in general there is not any "constant" area of the stack. But that's okay, because what const
really means is "I promise not to try to modify this". It does not mean "put this in read-only memory so that we're guaranteed to get a bus error if I goof".
There's no readonly stack segment, because it would have to be writable for the initializations, which happen every time the function is entered. Every function call would have an unreasonable amount of overhead, asking the kernel to change the page protection, initialize the variables, then change it back.
rodata works because the statically allocated const variables are only initialized once.