As mentioned in the title, I am little confused if the type-qualifiers impact the storage location (stack, bss etc..) of the declarator.To describe more I am considering the following declarations.
int main()
{
const int value=5;
const char *str= "Constant String";
}
- In the above code, the default
storage-class-specifierisauto. - Hence it is assumed that these constants will be allocated in the
stack-frameofmainwhen it is created. - Generally, the
pointersto various memory locations in stack have the freedom to modify the values contained in it. - Hence from the above points it is understandable that, either the
type-qualifieradds some logic to preserve theconstantnature of the element stored (If so what is it?) or theconstantsare stored in aread-only-portionof memory.Please elaborate on this.
More detailed example
#include <stdio.h>
int main(void)
{
int val=5;
int *ptr=&val;
const int *cptr=ptr;
*ptr=10; //Allowed
//*cptr=10; Not allowed
//Both ptr and cptr are pointing to same locations. But why the following error?
//"assignment of read-only location ‘*cptr’"
printf("ptr: %08X\n",ptr);
printf("cptr: %08X\n",cptr);
printf("Value: %d\n",*ptr);
}
In the above example, both cptr and ptr pointing to the same location. But cptr is pointer to a const type qualified integer. While modifying the value of cptr, the compiler throws a error as "assignment of read-only location ‘*cptr’". But I am able to modify the same location with ptr, as in the output below.Please explain
ptr: BFF912D8
cptr: BFF912D8
Value: 10
In your first example:
Where the variable
valueand the string literal will be stored is left to the implementation. All that C standard guarantees is that these will stored in read-only memory which may in text segment, stack or anywhere.In your second case:
When you try to modify
*cptr, the compiler doesn't care whether the actual location pointed bycptris a read-only or writable. All it cares is that the type qualifierconstusing which it thinks the location pointed to bycptris read-only.Another variant:
In this case, the compiler allows modifying a const value through a pointer. But this is undefined behaviour.