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

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

问题描述

我真的有很大的问题,理解 char * 最近。假设我做了一个递归函数来回复一个 char * ,但是根据我初始化它,我得到一些访问违例,在我的C ++引擎中,我didn'

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
第一种情况,我得到了尝试交换字母时违反访问权限:

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

char * bob = "hello";

CASE 2 然后我尝试使用它

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] = '\0';

CASE 4 这样工作,所以我告诉自己为什么不工作

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

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

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\0";

因为您正在更改指针而不复制数据。你想要的是这样:

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天全站免登陆