...
At compile time, string literals are used to create an array of static duration and sufficient length to contain the character sequence and a null-termination character. It is unspecified wehether these arrays are distinct. The behavior is undefined if a program attempts to modify string literals but frequently results in an access violation as string literals are typically stored in read-only memory.
Non-compliant Code Example
Do not attempt to modify a string literal. In the following example, the char pointer p
is initialized to the address of the static string. Attempting to modify the string literal result results in undefined behavior.
Code Block |
---|
char *p = "string literal"; p[0] = 'S'; |
Compliant Solution
As an array initializer, a string literal specifies the initial values of characters in an array (as well as the size of the array). The following 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.
Code Block |
---|
char a[] = "string literal"; a[0] = 'S'; |
Consequences
Abnormal program termination.
Denial-of-service attack.
References
- ISO/IEC 9899-1999 Section 6.4.5 String literals
- Summit 95 comp.lang.c FAQ list - Question 1.32