...
At compile time, string literals are used to create an array of static storage duration of sufficient length to contain the character sequence and a null-termination character. It is unspecified whether these arrays are distinct. The behavior is undefined if a program attempts to modify string literals but frequently results in an access violation because string literals are typically stored in read-only memory. See also undefined behavior 33 of Annex J of C11the C standard [ISO/IEC 9899:2011].
Do not attempt to modify a string literal. Use a named array of characters to obtain a modifiable string.
...
As an array initializer, a string literal specifies the initial values of characters in an array , as well as the size of the array. (See STR36-C. Do not specify the bound of a character array initialized with a string literal.) This code creates a copy of the string literal in the space allocated to the character array a
. The string stored in a
can be safely modified.
...
In this noncompliant example, the non-const
char*
result of the strrchr()
function is used to modify the object pointed to by pathname
. Since Because the pointer points to a string literal, the effects of the modification are undefined and are likely to cause a signal, such as SIGSEGV
, to be generated for the process if the object is stored in read-only memory.
...
A compliant solution avoids modifying a const
object, even if it is possible to obtain a non-const
pointer to such an object by calling a standard C library function, such as strrchr()
. To reduce the risk of callers of get_dirname()
passing constant objects to the function, the argument is declared to be a non-const
pointer. While Although converting a string literal to non-const
char*
is permitted by the language, conforming compilers could issue a diagnostic for such code. See also EXP05-C. Do not cast away a const qualification.
...
[Summit 1995] comp.lang.c FAQ list, Question 1.32
[Plum 1991] Topic 1.26, "strings - string strings—string literals"
...