char * const p = "hello";
defines a constant pointer p
and initialises it with the memory address of a constant string "hello"
which is inherently of type const char *
. By this assignment you are discarding a const
qualifier. It's valid C, but will lead to undefined behaviour if you don't know what you are doing.
Mind that const char *
forbids you to modify the contents of the memory being pointed to, but does not forbid to change the address while char * const
permits you to modify the contents, but fixes the address. There is also a combo version const char * const
.
Although this is valid C code, depending on your OS placement and restrictions on "hello"
it may or may not end up in writable memory. This is left undefined. As a rule on thumb: constant strings are part of the executable program text and are read-only. Thus attempting to write to *p
gives you a memory permission error SIGSEGV
.
The correct way is to copy the contents of the string to the stack and work there:
char p[] = "hello";
Now you can modify *p
because it is located on the stack which is read/write. If you require the same globally then put it into the global scope.