且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我的 char* 是可写的,有时只能在 C++ 中读取

更新时间:2022-04-17 02:25:55

关键是这些指针有的指向分配的内存(读/写),有的指向字符串常量.字符串常量存储在与分配的内存不同的位置,并且不能更改.大多数时候.系统中的漏洞通常是代码或常量被更改的结果,但那是另一回事.

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.

无论如何,关键是使用 new 关键字,这是在读/写内存中分配空间,因此您可以更改该内存.

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.

这个说法是错误的

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");

strncpy(bob,"hello",6);

此处不需要 nul,因为字符串常量 "hello" 将由编译器放置 null.

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