Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

cstring - Why is my char* writable and sometimes read only in C++

I have had really big problems understand the char* lately. Let's say I made a recursive function to revert a char* but depending on how I initialize it I get some access violations, and in my C++ primer I didn't find anything giving me the right path to understand so I am seeking your help.

CASE 1 First case where I got access violation when trying to swap letters around:

char * bob = "hello";

CASE 2 Then I tried this to get it work

char * bob = new char[5];
bob[0] = 'h';
bob[1] = 'e';
bob[2] = 'l';
bob[3] = 'l';
bob[4] = 'o';

CASE 3 But then when I did a cout I got some random crap at the end so I changed it for

char * bob = new char[6];
bob[0] = 'h';
bob[1] = 'e';
bob[2] = 'l';
bob[3] = 'l';
bob[4] = 'o';
bob[5] = '';

CASE 4 That worked so I told myself why wouldn't this work then

 char * bob = new char[6];
 bob = "hello";

CASE 5 and it failed, I have also read somewhere that you could do something like

char* bob[];

Then add something to that. My question is why do some fail and other not, and what is the best way to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The key is that some of these pointers are pointing at allocated memory (which is read/write) and some of them are pointing at string constants. String constants are stored in a different location than the allocated memory, and can't be changed. Well most of the time. Often vulnerabilities in systems are the result of code or constants being changed, but that is another story.

In any case, the key is the use of the new keyword, this is allocating space in read/write memory and thus you can change that memory.

This statement is wrong

char * bob = new char[6];
bob = "hello";

because you are changing the pointer not copying the data. What you want is this:

char * bob = new char[6];
strcpy(bob,"hello");

or

strncpy(bob,"hello",6);

You don't need the nul here because a string constant "hello" will have the null placed by the compiler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...