String literals: pointer vs. char array
You can look at string literal as "a sequence of characters surrounded by double quotes".
This string should be treated as read-only and trying to modify this memory leads to undefined behavior. It's not necessarily stored in read only memory, and the type is char[]
and not const char[]
, but it is still undefined behavior. The reason the type is not const
is backwards compability. C didn't have the const
qualifier in the beginning. In C++, string literals have the type const char[]
.
So how come that you get segmentation fault?
- The main point is that
char *ptr = "string literal"
makesptr
to point to the read-only memory where your string literal is stored. So when you try to access this memory:ptr[0] = 'X'
(which is by the way equivalent to*(ptr + 0) = 'X'
), it is a memory access violation.
On the other hand: char b[] = "string2";
allocates memory and copies string "string2"
into it, thus modifying it is valid. This memory is freed when b
goes out of scope.
Have a look at Literal string initializer for a character array