C Language Modify string literal


Example

In this code example, the char pointer p is initialized to the address of a string literal. Attempting to modify the string literal has undefined behavior.

char *p = "hello world";
p[0] = 'H'; // Undefined behavior

However, modifying a mutable array of char directly, or through a pointer is naturally not undefined behavior, even if its initializer is a literal string. The following is fine:

char a[] = "hello, world";
char *p = a;

a[0] = 'H';
p[7] = 'W';

That's because the string literal is effectively copied to the array each time the array is initialized (once for variables with static duration, each time the array is created for variables with automatic or thread duration — variables with allocated duration aren't initialized), and it is fine to modify array contents.