Modify string literal
suggest changeIn 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Modify string literal
Table Of Contents
5 Arrays
12 Assertion
13 Linked lists
15 X-macros
17 Pointers
18 Structs
22 Compilation
24 Bit-fields
25 Strings
30 Valgrind
31 Typedef
35 Boolean
38 Declarations
47 Atomics
49 Enumerations
55 Side effects
57 Constrains
58 Inlining
59 Unions
63 Comments
64 Contributors