Stack overflow

From Wikipedia, the free encyclopedia

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, usually determined at the start of the program, and depends on the language, computer, and amount of available memory. When too much memory is used (i.e. when the program tries to access memory that is outside the region reserved for the call stack), the stack is said to "overflow", typically resulting in program crash if no provision is made for this occurrence in the program. Stack overflows can occur either because too many functions are called (and haven't finished) in a computer program, or a function allocates too much space for automatic variables.

The most common cause of stack overflows is infinite recursion. Language implementations with tail-call optimization allow infinite recursion of a specific sort — tail recursion — to occur without stack overflow, because tail-recursive calls do not take up additional stack; they are optimized to "GOTOs with arguments".

Another common cause for stack overflow is an attempt to create a large array on the stack. The work-around to this usually is to allocate the memory for the array using dynamic memory allocation, which often has a larger pool of memory, and the allocation explicitly fails if there is insufficient memory.

[edit] C/C++ examples

Infinite recursion
int f(){
  g();
}
int g() {
  f();  
}

f() calls g(), which in turn calls f() and so on. Eventually, the stack overflows.

Large Array Allocation on the stack
int main() {
  int n[10000000]; // array is too large 
  int j =0; //j's address exceeds the stack's limits, error
}

[edit] See also

In other languages