In order to improve my knowledge regarding pointers and constants, I wrote the following code:
int main() {
const int value = 2;
int *pvalue = &value;
*pvalue = 3;
printf("value: %d\n", value);
printf("*pvalue: %d\n", *pvalue);
printf("&value: %p\n", &value);
printf("pvalue: %p", pvalue);
return 0;
}
From what I understand, value
cannot be edited directly because it is declared as a const
. Nonetheless, it can be edited indirectly through *pvalue
. At least, it's how I understand the warning below thrown by the compiler on line int *pvalue = &value;
.
warning: initialization discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]|
However, when I run the code, here's the output I get:
value: 2
*pvalue: 3
&value: 000000000060FE1C
pvalue: 000000000060FE1C
value
and *pvalue
are different, but it seems like they are pointing to the same memory address.
What am I missing?
CodePudding user response:
You are ignoring the compiler diagnosis, which you should not.
Anyway, with const
you prohibit write access to the qualified object. And the compiler will not accept value = 23;
, for sure.
But by the pointer you removed this limitation, and invoked Undefined Behavior. On the actual target, since the variable is most probably located on the stack, it is writable by hardware means. Such a behavior is included in "undefined".
Put it into static memory, and most probably you will get a runtime exception, because the variable will be allocated in write-protected memory.