#include <stdio.h>
#include <stdlib.h>
const int * func()
{
int * i = malloc(sizeof(int));
(*i) = 5; // initialize the value of the memory area
return i;
}
int main()
{
int * p = func();
printf("%d\n", (*p));
(*p) = 3; // attempt to change the memory area - compiles fine
printf("%d\n", (*p));
free(p);
return 0;
}
Why does the compiler allow me to change (*p) even if func() returns a const pointer?
I’m using gcc, it shows only a warning on the int * p = func(); line : “warning: initialization discards qualifiers from pointer target type”.
Thanks.
Your program is not valid. C forbids implicitly removing a
constlike that, and in conformance to the spec GCC should give you at least a warning for that code. You would need a cast to remove theconst.Having consumed a warning for that, you can however rely on the program to work (although not anymore from a Standards point of view), because the pointer is pointing to a malloc’ed memory area. And you are allowed to write to that area. A
const T*pointing to some memory doesn’t mean that the memory is thereafter marked immutable.Note that the Standard doesn’t require a compiler to reject any program. The Standard merely requires compilers to sometimes emit a message to the user. Whether that’s an error message or warning and how the message is emitted and whatever happens after that emission, isn’t specified by the Standard at all.