ls0f / my-issues

0 stars 0 forks source link

为什么stack overflow 却提示segmentation fault #27

Open ls0f opened 8 years ago

ls0f commented 8 years ago

什么是segmentation fault

首先得了解什么是segmentation fault?

what-is-segmentation-fault

Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” It’s a helper mechanism that keeps you from corrupting the memory and introducing hard-to-debug memory bugs. Whenever you get a segfault you know you are doing something wrong with memory – accessing variable that has already been freed, writing to a read-only portion of the memory, etc. Segmentation fault is essentially the same in most languages that let you mess with the memory management, there is no principial difference between segfaults in C and C++.

也就是非法内存访问,会导致segmentation fault

触发segmentation fault

看下面的程序:

#include<stdio.h>

void func(char *p)
{
        char c = 'a';
        p = &c;
}

int main()
{
        char *p = NULL;
        func(p);
        printf("p=%c\n", *p);
}

执行func函数,指针p指向变量c的内存地址,但是func函数执行完后,变量c占用的内存就从stack空间释放了,printf调用试图去读取已经释放的地址,就会造成segmentation fault错误。

stack overflow

看下面的程序:

#include<stdio.h>

#define length  1024*1024*100

int main()
{
        int array[length] ;
        return 0;
}

这里我声明一个400MB空间的数组,肯定会造成stack溢出。但是执行的时候抛出的却不是stack overflow错误,而是:

[1] 75916 segmentation fault ./ex

what-is-the-difference-between-a-segmentation-fault-and-a-stack-overflow

Stack overflow is [a] cause, segmentation fault is the result.

At least on x86 and ARM, the "stack" is a piece of memory reserved for placing local variables and return addresses of function calls. When the stack is exhausted, the memory outside of the reserved area will be accessed. But the app did not ask the kernel for this memory, thus a SegFault will be generated for memory protection.

大致意思就是栈溢出造成了内存的非法访问。

可以通过ulimit -a查看stack size大小,通过ulimit -s改变大小。

http://www.cs.nyu.edu/exact/core/doc/stackOverflow.txt