段错误不上来访问外结合的内存后,立即 [英] Segmentation Fault doesn't come up immediately after accessing out-of-bound memory

查看:152
本文介绍了段错误不上来访问外结合的内存后,立即的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写这片code,并被quicly期待分段错误,但似乎我可以访问的内存块,我不应该能。

I wrote this piece of code and was expecting a segmentation fault quicly, but it seems I am allowed to access pieces of memory I shouldn't be able to.

#include<stdio.h>
int main()
{
    int tab[1];
    tab[0]=42;
    int i;
    //Expecting Seg Fault from i==1...
    for(i=0;;i++)
    {
        printf("%d \t %d \n", i, tab[i]);
    }
    return 0;
}

我使用的编译:

gcc -Wall -Wextra my_code.c -o segfault && ./segfault

在执行时,变量 I 让我的细分故障之前达到1000阶值。

Upon execution, variable i reaches values of order 1000 before I get my Segmentation Fault.

我的问题是:为什么我能读设置页至今

My question is: Why am I able to read tab so far ?

PS:使用的#include&LT;文件stdlib.h&GT; ,并宣布为int *标签=(INT *)malloc的(的sizeof(int)的) ; 不会改变任何东西...

PS: Using #include <stdlib.h> and declaring int * tab = (int*)malloc(sizeof(int)); doesn't change anything...

谢谢,最好成绩。

推荐答案

您阵标签堆栈上将位于什么地方。当您打印过去数组的结尾,你实际上是在栈上打印其它存储位置的值。

Your array tab will be located someplace on the stack. When you print past the end of the array, you are actually printing values of other memory locations on the stack.

大约需要1000次迭代得到赛格故障原因是,堆在页面映射和页面通常是在大小为4 KB的原因。一旦你阅读约1000整数,你周围4000字节过去,你应该在哪里,你已经越过未映射页。从映射的页面阅读是实际触发赛格故障。

The reason it takes around 1000 iterations to get the seg fault is that the stack is mapped in pages, and pages are usually 4 KB in size. Once you read around 1000 ints, you are around 4000 bytes past where you should be and you have crossed over to an unmapped page. Reading from an unmapped page is what actually triggers the seg fault.

注意到,我只解释发生了什么事您的系统。但不保证该堆栈将在页面或页面被映射将在大小4字节。从技术上讲,你正在引发未定义行为,任何事情都有可能发生。您可能会发现照亮做的printf(%P \\ N,&安培;标签由[i]); 在每次迭代,看看它是什么之前打印的最后一个地址你得到的赛格故障。如果我是对的4 KB页,可以看到印刷将在 FFC 结束,因为这将是页面上的最后4个字节的最后一个地址。

Take note that I am only explaining what happened on your system. There is no guarantee that the stack will be mapped in pages or that the pages will be 4 KB in size. Technically, you are triggering undefined behavior and anything can happen. You might find it illuminating to do printf("%p\n", &tab[i]); on each iteration and see what is the last address it prints before you get the seg fault. If I was right about the 4 KB pages, the last address you see printed will end in ffc because that will be the last 4 bytes on the page.

这篇关于段错误不上来访问外结合的内存后,立即的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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