Course contentsShow
← C
Lesson 531 of 1,2198. Memory ManagementFree lesson

Understanding stack overflow

Understanding stack overflow

What you'll learn: How excessive function calls or large local variables can crash your program by running out of dedicated scratchpad memory.

The stack is a finite bucket

Imagine your computer's memory for running functions is like a vertical tube. Every time you call a function, you drop a "frame" into the tube. This frame holds that function's local variables and instructions on where to return when it’s finished. When the function ends, the frame is lifted out, freeing up space.

This tube—the Stack—is incredibly fast, but it has one major limitation: it has a fixed, relatively small size. If you keep dropping frames into the tube without removing any, you will eventually hit the top and spill over. In programming, this "spill" is a Stack Overflow, and it almost always results in your program crashing instantly with a "Segmentation Fault."

How it happens: The infinite loop

The most common way to trigger a stack overflow is through recursion—a function that calls itself—without a proper exit condition. Each new call adds a new layer to the stack. If the function calls itself thousands of times, the stack runs out of room before the first function ever gets a chance to finish and clear its space.

#include <stdio.h>

void unintended_infinity() {
    int large_array[1000]; // Local variables live on the stack
    unintended_infinity();  // The function calls itself forever
}

int main() {
    // This will crash quickly as the stack fills up
    unintended_infinity();
    return 0;
}

Too much of a good thing

You can also cause a stack overflow without recursion by declaring a massive local variable. Because the stack is meant for small, temporary data, trying to fit a multi-megabyte array inside a function is like trying to fit a mattress into our memory tube; it simply won't fit, and the program will fail to start that function.

When you need to store massive amounts of data, you move away from the Stack and use the Heap, which we will cover in the next lesson.

Key takeaway

A stack overflow occurs when the fixed memory area for function calls fills up, usually due to infinite recursion or oversized local variables.