I'm a little perplexed why the following blows up:
char* c = "Hello World!";
*c = 'h';
When I allocate the string on the heap it works. So I'm just curious what wrong with my initial version.
I'm a little perplexed why the following blows up:
char* c = "Hello World!";
*c = 'h';
When I allocate the string on the heap it works. So I'm just curious what wrong with my initial version.
char* c = "Hello World!";
is a pointer to a string literal which is typically stored in a read-only memory segment. Attempting to modify it is undefined behaviour. Pointers to string literals such as this should more properly be defined as
const char *c = "Hello World!";
but the const
is often omitted (in C, at least).
char* c = "Hello World!";
Here c
is a pointer which point to a literal string so you can not modify it
You can use this instead
char c[] = "Hello World!";
*c = 'h',
c
here is an array of char and contains the chars of the string "Hello World!"
so you can modify it.
You're pointing c
to a string literal, most likely stored in the read only memory segment, you can't change it. Even if you can physically change it, as per the C spec:
6.4.5 (String Literals)
If the program attempts to modify [a string literal], the behavior is undefined.
If you allocate memory on the heap (or stack) and then copy the string to that location, you can change it as you see fit.
Modifying string literals is undefined behaviour. The main reason for that is that the compiler is permitted to place "Hello World!"
in read-only memory.
On the other hand, the following is fine:
char c[] = "Hello World!";
*c = 'h';
Strings like char * c = "Hello";
are string constants and are stored in read only data segment so you can't modify them [But some compilers do allow that]
Heap allocated strings are not in read only segments and are hence free to be modified.