Stack overflow
In software, a stack overflow occurs when too much memory is used on the call stack. In many programming languages the call stack contains a limited amount of memory, usually 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 too much memory is used on the call stack the stack is said to overflow; typically resulting in a program crash.[1] This class of software bug is usually caused by one of two types of programming errors.[2]
Contents |
Infinite recursion
The most common cause of stack overflows is excessively deep or infinite recursion. Languages, like Scheme, which implement tail-call optimization allow infinite recursion of a specific sort — tail recursion — to occur without stack overflow. This works because tail-recursion calls do not take up additional stack space.[3]
Very large stack variables
The other major cause of a stack overflow results from an attempt to allocate more memory on the stack than will fit. This is usually the result of creating local array variables that are far too large. For this reason arrays larger than a few kilobytes should be allocated dynamically instead of as a local variable.[4]
Stack overflows are made worse by anything that reduces the effective stack size of a given program. For example, the same program being run without multiple threads might work fine, but as soon as multi-threading is enabled the program will crash. This is because most programs with threads have less stack space per thread than a program with no threading support. Similarly, people new to kernel development are usually discouraged from using recursive algorithms or large stack buffers.[5][6]
C/C++/Objective C/Objective C++ examples
- Keep calling itself
void a() { a(); } int main() { a(); return 0; }
This code calls a(), and a() calls itself, which will never end.
- Infinite recursion
void f(void); void g(void); int main(void) { f(); return 0; } void f(void) { g(); } void g(void) { f(); }
f()
calls g()
, which in turn calls f()
and so on. Eventually, the stack overflows.
- Large stack variables
// Large Array Allocation on the stack: int main(void) { int n[10000000]; /* array is too large */ int j =0; /* j's address exceeds the stack's limits, error */ return 0; }
See also
References
- ^ Burley, James Craig (1991-06-01). "Using and Porting GNU Fortran".
- ^ Danny, Kalev (2000-09-05). "Understanding Stack Overflow".
- ^ "An Introduction to Scheme and its Implementation" (1997-02-19).
- ^ Feldman, Howard (2005-11-23). "Modern Memory Management, Part 2".
- ^ "Kernel Programming Guide: Performance and Stability Tips". Apple Inc. (2006-11-07).
- ^ Dunlap, Randy (2005-05-19). "Linux Kernel Development: Getting Started".