Course contentsShow
← Computer Science
Lesson 2077 of 2,87247. Memory Management in LanguagesFree lesson

Stack Growth and Limitations

Stack growth direction, size limits, stack overflow conditions, and why recursion depth is bounded by stack size.

Stack Growth and Limitations

You'll learn why the stack can't grow forever and what happens when programs push it too far.

How the Stack Grows

The stack doesn't expand arbitrarily—it has a direction and size limit. On most architectures, the stack grows downward from high memory addresses toward lower ones. Each function call pushes a new activation record (stack frame) onto the stack, moving the stack pointer in that downward direction.

Think of the stack like a physical spring: you can compress it (add frames), but only so far before something breaks.

Size Limits

Operating systems allocate a fixed maximum size for the stack, typically a few megabytes. This limit exists because:

  • Physical memory is finite
  • The stack shares address space with other memory regions
  • Stack size is determined at program startup (or thread creation)

Stack Overflow

When your program exhausts the available stack space, a stack overflow occurs—the program crashes with an error like "segmentation fault" or "stack overflow exception."

Common causes:

  • Deep recursion: Each recursive call adds a frame. A recursive function with 10,000 calls might easily exceed the stack limit.
  • Large local variables: Allocating big arrays on the stack consumes space quickly.
  • Infinite recursion: Bugs that never hit a base case will eventually overflow.

Why Recursion Depth Is Bounded

Since each recursive function call creates a new stack frame, and the stack has finite size, recursion depth is inherently limited by stack capacity. A function that recurses 100,000 times will likely fail, while an iterative loop can run millions of iterations using minimal stack space (just one frame).

Key Takeaway: The stack grows in a fixed direction with a hard size limit imposed by the OS, making deep recursion and large local allocations potential sources of stack overflow errors.