What is a stack overflow?

From Wikipedia:

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 stack is a data structure that keeps record of the point the subroutines of a program should return control to when they finish executing. The return addresses are pushed in the stack as the subroutines are being invoked, when the subroutine finish its execution the return address is pulled from the stack. If there are many subroutines and there is no space in the stack a stack overflow happens.

Also in the stack is intended to store local variables so if a local variable is too large is more probable the stack doesn’t have space to store it, if this is the case a stack overflow happens too.

Wikipedia includes a nice diagram picturing the stack when a DrawLine subroutine is called from another subroutine called DrawSquare, I hope this picture helps to understand better the stack structure.

stack diagram

There are two main causes of a stack overflow: deep function recursions and excessively large stack variables. Since these are common terms in almost all programming languages a stack overflow can happen besides the complexity of the language.

Guffa contribution: The stack doesn’t have anything to do with garbage collection. Modern applications have a larger stack, which makes it slightly less likely to get a stack overflow, but other than that there is no difference.

Leave a Comment