...
In this noncompliant code example, the char
pointer p
is str
is initialized to the address of a string literal. Attempting to modify the string literal is undefined behavior:
Code Block | ||||
---|---|---|---|---|
| ||||
char *pstr = "string literal"; pstr[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. (See STR11-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
str
. The string stored in a
can str
can be modified safely.
Code Block | ||||
---|---|---|---|---|
| ||||
char astr[] = "string literal"; astr[0] = 'S'; |
Noncompliant Code Example (POSIX)
...