Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: string ptrs changed from p&a to str

...

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
bgColor#FFcccc
langc
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
bgColor#ccccff
langc
char astr[] = "string literal";
astr[0] = 'S';

Noncompliant Code Example (POSIX)

...