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. This class of software bug is usually caused by one of two types of programming errors.
Infinite recursionMain article: 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]
An example of infinite recursion in C.
int foo() {
return foo();
}
The function foo, when it is invoked, continues to invoke itself, using additional space on the stack each time, until the stack overflows resulting in a segmentation fault.[4]
[edit] Very large stack variablesThe 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.[5]
An example of a very large stack variable in C:
int foo() {
double x[1000000];
}
The declared array consumes 8 megabytes of data (assuming each double is 8 bytes); if this is more memory than is available on the stack, a stack overflow will occur.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.