Course contentsShow
← Computer Science
Lesson 224 of 2,8725. Functions and ModularityFree lesson

Call Stack and Stack Overflow

Understand how the call stack grows with recursion and what causes stack overflow errors.

Call Stack and Stack Overflow

What you'll learn: How recursive function calls pile up in memory and what happens when you run out of space.


When you call a function, your program doesn't forget where it came from—it needs to remember how to return. This memory management happens on the call stack, a special region of memory that works like a stack of plates.

How the Call Stack Works

Every time a function is called, the program adds a new "frame" to the top of the stack. This frame stores:

  • The function's local variables
  • Where to return when the function finishes
  • Any parameters passed to the function

When the function returns, its frame is removed (popped off the stack), and control goes back to the previous function.

The Problem with Deep Recursion

In recursive functions, each call adds another frame to the stack before any of them finish. If you call factorial(5), it calls factorial(4), which calls factorial(3), and so on. All five frames sit on the stack simultaneously until the base case is reached.

Imagine a tower of books: Each recursive call adds another book to the top. If your recursion goes too deep (say, factorial(100000)), the tower collapses—you've run out of stack space. This is called a stack overflow error.

What Causes Stack Overflow

  • No base case (infinite recursion)
  • Base case never reached
  • Recursion depth too large for available memory

Unlike iteration, which reuses the same memory space, recursion consumes more stack space with each call.

Key Takeaway: The call stack grows with each recursive call; too many nested calls without returning cause a stack overflow error, crashing your program.