p
points to a character string literal which should not be modified; a
is a character array which may be modified.
- The character string literal may well be in a read-only section of your program (often the 'text' segment along with the rest of the code), whereas the character array is stored in modifiable memory.
- You are not allowed to modify string literals; doing so invokes undefined behaviour.
- Often, the string is stored in the 'text' segment, along with the executable code.
It is important to realize that the standard simply says 'thou shalt not modify string literals' (more or less), and attempts to do say may lead to any effect. It is possible that your program will crash (segmentation violation or equivalent); it is possible that your code will modify the literal; it is possible that your code will neither crash nor change the literal. Note that if there are multiple places in the program where the literal occurs, it is possible that modifying one will modify them all — the compiler is allowed to have string literals sharing space in memory. They don't even have to be identical; "string literal"
and "literal"
could be pointers to different parts of the same string in memory.
ISO/IEC 9899:2011, §6.4.5 String literals says:
¶6 In translation phase 7, a byte or code of value zero is appended to each multibyte
character sequence that results from a string literal or literals. The multibyte character
sequence is then used to initialize an array of static storage duration and length just
sufficient to contain the sequence. [...]
¶7 It is unspecified whether these arrays are distinct provided their elements have the
appropriate values. If the program attempts to modify such an array, the behavior is
undefined.