A range of memory that the operating system has pre-allocated for the program. If a program modifies memory of another program’s allocated memory, this is a Segmentation Fault and the program is killed by the OS.

Properties, Pros and Cons

PropertiesImplication
Data is added and removed using a stack data structuređźš« Single-threaded. Cannot share memory between concurrent executions
Data is stored in a compact fashionâś… Saves space, by avoiding memory fragmentation
âś… Improved performance with caches1
Variable sizes need to be known ahead of timeIs needed for handling the return value of function calls and local data
âś… Fast allocation times
đźš« No dynamic-type sizes are allowed
Size is pre-allocated and fixed2đźš« Stack overflow may occur with large data or heavy recursion

Iterative vs Recursive Solutions

Stacks are vulnerable to overflowing with recursive solutions if:

  • there is no base case (infinite recursion)
  • it takes too many stacks to end the recursion3

Stack size determination

This is usually determined by the operating system with a default value, but it can be configured during compilation time.

Terminology

TerminologyDescription
Stack originPointer to the starting address of a program’s stack
Stack framesA concept which allows programs to group data in memory based on the execution context
Stack pointerA pointer to the end of occupied memory in a program’s stack
Stack registerA modern hardware feature to quickly keep track of a stack pointer’s value.

This allows for much faster execution than storing the pointer in memory.
Return linksA pre-allocated memory address in the stack for the return value of a function call. This is why functions need to have known, fixed-length return types.

Footnotes

  1. this is because caches are a range in memory. The more things are stored within that range, the more likely for a cache hit to occur ↩

  2. In most programming languages ↩

  3. an exception to this is an optimization known as end-tail recursion. ↩