Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value of character pointer

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"?

like image 946
D Gul Avatar asked Jan 28 '23 16:01

D Gul


1 Answers

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.

like image 133
DeiDei Avatar answered Feb 01 '23 12:02

DeiDei