为什么我越来越阅读和未分配的内存读写权限? [英] Why I'm getting read and write permission on unallocated memory?

查看:160
本文介绍了为什么我越来越阅读和未分配的内存读写权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面code片段的行为,

I'm confused on the behavior of below code snippet,

我已经声明了一个字符指针,它指向分配的大小(1 *的sizeof(char)的)的内存位置。

I have declared a char pointer and pointed it to a memory location of allocated size (1 * sizeof(char)) .

char *src ;
src = (char*)malloc(1 * sizeof(char));
strcpy(src,"Copy text");

虽然我只分配 1 *的sizeof(char)的内存我能成功地复制整个字符串,还我越来越读,对整个写权限存储器区域的复制文本是present。

Even though I have only allocated memory of 1*sizeof(char) I can succesfully copy the entire string and also I'm getting read and write permission on the entire memory area where "Copy text" is present .

即下面的code打印修改value.ie,它打印复制RRxt

i.e the below code prints the modified value.ie, it prints "Copy RRxt".

src[5] = 'R';
src[6] = 'R';
printf("%s \n" , src);

所以我很困惑,为什么我没有得到段错误在上面的代码中的错误。

So I'm confused why I didn't get "Segmentation fault" error on the above snippet.

请注意:我使用GCC编译器v4.6.3

Note: I'm using GCC compiler v4.6.3

推荐答案

这是因为的malloc 的工作原理是 16或32个字节的块因为这种策略使得内存访问更加高效。因此,当你分配 1个字节未来15个字节可能可能是你的了。

This is because malloc works by chunks of 16 or 32 bytes because this strategy makes memory accesses more efficient. Therefore when you allocate 1 byte the next 15 bytes may probably be yours.

不过,我不会推荐作弊知道这一招,但正确分配字节适量。

However I would not recommend cheating knowing this trick but correctly allocating the right amount of bytes.

这篇关于为什么我越来越阅读和未分配的内存读写权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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