Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Do not attempt to modify a string literal. Use a named array of characters to obtain a modifiable string.

Non-Compliant Code Example

In this 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.

...

Include Page
c:STR30 NCCE 1
c:STR30 NCCE 1

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). 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.

Code Block
char a[] = "string literal";
a[0] = 'S';

Non-Compliant Code Example

In this non-compliant example, the mktemp() function modifies its string argument.

...