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 non-compliant code example, the char pointer p is initialized to the address of a string literal. Attempting to modify the string literal results in undefined behavior.

Code Block
bgColor#FFcccc

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). 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
bgColor#ccccff

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

Non-Compliant Code Example

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

Code Block
bgColor#FFcccc

mktemp("/tmp/edXXXXXX");

Compliant Solution

Instead of passing a string literal, use a named array:

Code Block
bgColor#ccccff

static char fname[] = "/tmp/edXXXXXX";

mktemp(fname);

...

Risk Assessment

Modifying string literals can lead to abnormal program termination and possibly denial-of-service attacks.

...