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);
}
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.
什么是segmentation fault
首先得了解什么是segmentation fault?
what-is-segmentation-fault
也就是非法内存访问,会导致
segmentation fault
。触发segmentation fault
看下面的程序:
执行func函数,指针p指向变量c的内存地址,但是func函数执行完后,变量c占用的内存就从stack空间释放了,printf调用试图去读取已经释放的地址,就会造成segmentation fault错误。
stack overflow
看下面的程序:
这里我声明一个400MB空间的数组,肯定会造成stack溢出。但是执行的时候抛出的却不是stack overflow错误,而是:
[1] 75916 segmentation fault ./ex
what-is-the-difference-between-a-segmentation-fault-and-a-stack-overflow
大致意思就是栈溢出造成了内存的非法访问。
可以通过
ulimit -a
查看stack size大小,通过ulimit -s
改变大小。http://www.cs.nyu.edu/exact/core/doc/stackOverflow.txt