Change character pointer value

Why does this work?

char*p = new char[4];
p = "hey";
p = "jey";

But is that not so?

char* p = new char[4];
p = "hey";
p[0] = 'j';

The second example results in a segmentation error.

In the first example, "jey" is being rewritten "hey"?

+4
source share
2 answers

A string literal such as "hey"or "jey"is a constant that you cannot change.

Statements

p = "hey";
p = "jey";

make ppoints to the first element of the assigned string. Although the language allows this, you are losing pointer information received from new, and now you have a memory leak.

You have the same problem in the second example, but you get segfault when you try to change a string literal with

p[0] = 'j';

, "hey" 0x01, 0x02 0x03 p 0x01. p[0] = 'j', , 0x01, , segfault.

+5

"hey" - const char*, , , .

char* p = new char[4]; //pointer point on virtual memory 
p = "hey"; //pointer point on code (read only) memory , previous allocation lost.
p[0] = 'j'; //write on read only memory.

, seg.

, , char * point to const char *. , , , .

std::string

std::string str;
str = "hey"; //the text is copied by operator =
str[0] = 'j';//byte is changed by operator [] 

, :

char* p = new char[4]; //allocate virtual memory (read/write).
strcpy(p ,"hey"); //don't point to read only code segment, copy it to the read/write virtual memory.
p[0] = 'j'; //change a single byte on pointed memory.

p , .

BTW: . new delete

delete [] p; //you must free the allocated array.
+2

Source: https://habr.com/ru/post/1693568/


All Articles