Stack overflow explained

In software, a stack overflow occurs if the call stack pointer exceeds the stack bound. The call stack may consist of a limited amount of address space, 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.[1]

Causes

Infinite recursion

The most-common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack.[2]

An example of infinite recursion in C.int foo

The function foo, when it is invoked, continues to invoke itself, allocating additional space on the stack each time, until the stack overflows resulting in a segmentation fault.[2] However, some compilers implement tail-call optimization, allowing 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]

Some C compiler options will effectively enable tail-call optimization; for example, compiling the above simple program using gcc with -O1 will result in a segmentation fault, but not when using -O2 or -O3, since these optimization levels imply the -foptimize-sibling-calls compiler option.[4] Other languages, such as Scheme, require all implementations to include tail-recursion as part of the language standard.[5]

Very deep recursion

A recursive function that terminates in theory but causes a call stack buffer overflow in practice can be fixed by transforming the recursion into a loop and storing the function arguments in an explicit stack (rather than the implicit use of the call stack). This is always possible because the class of primitive recursive functions is equivalent to the class of LOOP computable functions. Consider this example in C++-like pseudocode:

A primitive recursive function like the one on the left side can always be transformed into a loop like on the right side.

A function like the example above on the left would not be a problem in an environment supporting tail-call optimization; however, it is still possible to create a recursive function that may result in a stack overflow in these languages. Consider the example below of two simple integer exponentiation functions.

Both pow(base, exp) functions above compute an equivalent result, however, the one on the left is prone to causing a stack overflow because tail-call optimization is not possible for this function. During execution, the stack for these functions will look like this:

Notice that the function on the left must store in its stack exp number of integers, which will be multiplied when the recursion terminates and the function returns 1. In contrast, the function at the right must only store 3 integers at any time, and computes an intermediary result which is passed to its following invocation. As no other information outside of the current function invocation must be stored, a tail-recursion optimizer can "drop" the prior stack frames, eliminating the possibility of a stack overflow.

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, for example by creating local array variables that are too large. For this reason some authors recommend that arrays larger than a few kilobytes should be allocated dynamically instead of as a local variable.[6]

An example of a very large stack variable in C:int foo

On a C implementation with 8 byte double-precision floats, the declared array consumes 8 megabytes of data; if this is more memory than is available on the stack (as set by thread creation parameters or operating system limits), a stack overflow will occur.

Constrained environment

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. Because kernels are generally multi-threaded, people new to kernel development are usually discouraged from using recursive algorithms or large stack buffers.[7]

See also

External links

Notes and References

  1. Web site: Burley . James Craig . Using and Porting GNU Fortran . 1991-06-01 . dead . https://web.archive.org/web/20120206112619/http://sunsite.ualberta.ca/Documentation/Gnu/gcc-2.95.2/html_node/g77_597.html . 2012-02-06 .
  2. https://stackoverflow.com/questions/2685413/what-is-the-difference-between-a-segmentation-fault-and-a-stack-overflow/2685434#2685434 What is the difference between a segmentation fault and a stack overflow?
  3. Web site: An Introduction to Scheme and its Implementation . 1997-02-19 . dead . https://web.archive.org/web/20070810213035/http://www.federated.com/~jim/schintro-v14/schintro_73.html . 2007-08-10 .
  4. Web site: Using the GNU Compiler Collection (GCC): Optimize Options. 2017-08-20. 2017-08-20. https://web.archive.org/web/20170820201527/https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html. live.
  5. Richard Kelsey . August 1998 . Revised5 Report on the Algorithmic Language Scheme . Higher-Order and Symbolic Computation . 11 . 1 . 7–105 . 10.1023/A:1010051815785 . 2012-08-09 . William Clinger . Jonathan Rees . 3 . Rozas . G.J. . Adams Iv . N.I. . Friedman . D.P. . Kohlbecker . E. . Steele Jr. . G.L. . Bartley . D.H. . 14069423 . 2007-01-05 . https://web.archive.org/web/20070105152327/http://www.schemers.org/Documents/Standards/R5RS/ . live.
  6. Web site: Feldman . Howard . Modern Memory Management, Part 2 . 2005-11-23 . 2007-08-14 . 2012-09-20 . https://web.archive.org/web/20120920112622/http://onlamp.com/pub/a/onlamp/2005/11/23/memory-management-2.html . dead .
  7. Web site: Apple Inc. . Kernel Programming Guide: Performance and Stability Tips . 2014-05-02 . 2014-05-02 . 2014-05-03 . https://web.archive.org/web/20140503011953/https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/KernelProgramming/style/style.html#//apple_ref/doc/uid/TP30000905-CH208-TPXREF111 . live .