In software, a stack overflow occurs when too much memory is used on the call stack. The call stack contains a limited amount of memory, often determined at the start of the program. The size of the call stack depends on many factors, including the programming language, machine architecture, multi-threading, and amount of available memory. When a program attempts to use more space than is available on the call stack (that is, when it attempts to access memory beyond the call stack's bounds, which is essentially a buffer overflow), the stack is said to overflow, typically resulting in a program crash.
int foo() { return foo(); }
int foo() { double x[1000000]; }
递归和申请本地变量过大都容易引起栈溢出,须警惕。
Detail:Stack overflow(wiki)
举个例子:
#include <stdio.h> int main() { const int stackMaxSize = 1024 * 1024 * 50; // 50M char buf[stackMaxSize]; printf("run no error!\n"); return 0; }
运行结果:崩溃。
bash: line 1: 1814 Segmentation fault: 11 '/Users/yuming/Downloads/test' [Finished in 0.3s with exit code 139]
稍作修改,改为在堆上申请内存
#include <stdio.h> int main() { const int stackMaxSize = 1024 * 1024 * 50; // 50M char* buf = new char[stackMaxSize]; delete []buf; printf("run no error!\n"); return 0; }
运行结果:正常。
run no error! [Finished in 0.1s]
题外话:栈溢出漏洞很容易被入侵哦,大家小心为上。