Why does the above work?
char*p = new char[4];
p = "hey";
p = "jey";
But this doesn't?
char* p = new char[4];
p = "hey";
p[0] = 'j';
The second example results in a segmentation fault.
In the first example, is "jey" overwriting "hey"?
A string literal such as "hey" or "jey" is a constant, which you cannot modify.
The statements
p = "hey";
p = "jey";
make p point to the first element of the assigned string. While the language allows it, you lose the pointer information you got from new, and now you have a memory leak.
You have the same problem in the second example, but you get a segfault when you try to modify the string literal with
p[0] = 'j';
Imagine "hey" is stored in some read-only memory on addresses 0x01, 0x02 and 0x03 for the three characters and p points to 0x01. Doing p[0] = 'j' you are trying to change the value stored in address 0x01, but since it's read-only memory, you get the segfault.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With