Reputation: 669
Consider the following code:
char* str = "Hello World";
memcpy(str, "Copy\0", 5);
A segmentation fault occurs during the memcpy. However, using this code:
char str[12];
memcpy(str, "Hello World\0", 12);
memcpy(str, "Copy\0", 5);
The program does not produce a segmentation fault.
Does the problem arise from allocating the memory on the stack versus the data section?
Upvotes: 5
Views: 18935
Reputation:
char* str = "Hello World";
and
char str[12];
are two very different things. One allocates a pointer on the stack and an array in read-only "code segment". The pointer then points at the array. The other allocates the entire array on the stack, and there is no pointer.
Upvotes: 2
Reputation: 838296
When you use a string literal in gcc the value is placed in read-only memory and cannot be modified. Trying to modify it leads to undefined behaviour. Usually you will get a segmentation fault on Linux when you try to do this.
The second example works because you aren't modifying the string literal, you are modifying a copy of it that is stored in variable that is not read-only.
Upvotes: 14