为什么我的 char* 是可写的,有时只能在 C++ 中读取 [英] Why is my char* writable and sometimes read only in C++

查看:34
本文介绍了为什么我的 char* 是可写的,有时只能在 C++ 中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在理解 char* 方面遇到了很大的问题.假设我创建了一个递归函数来恢复 char* 但根据我如何初始化它,我会遇到一些访问冲突,并且在我的 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.

案例 1在尝试交换字母时遇到访问冲突的第一种情况:

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

char * bob = "hello";

CASE 2 然后我尝试了这个来让它工作

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 但是当我进行 cout 时,我最后得到了一些随机的废话,所以我将其更改为

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 那行得通,所以我告诉自己为什么这行不通

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

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

CASE 5 并且它失败了,我也在某处读到你可以做类似的事情

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?

推荐答案

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

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.

这篇关于为什么我的 char* 是可写的,有时只能在 C++ 中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆