Stack overflow

From Wikipedia, the free encyclopedia

A stack overflow occurs when too many functions are called in a computer program. The call stack can only contain a limited (albeit large) number of functions, depending on language and computer (limited at the very outside by the amount of memory available). If too many functions are called, the stack is said to "overflow", typically resulting in program crash if no provision is made for this occurrence in the program.

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.

[edit] C/C++ examples

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