Back to writing
Data Structure

Call Stack

Overview

The call stack is a stack data structure (LIFO) used to manage the execution order and state of function calls. The unit of data pushed onto the stack in a single operation is called a stack frame.

  • When a function is called, a stack frame is pushed onto the stack
  • When a function returns, its frame is popped off the stack
  • The last function called is the first to finish (LIFO: Last In, First Out)
  • If more space is used than the stack has been allocated, a "stack overflow" error occurs

Purpose

The purpose of the call stack is to remember where to return (the return address) after a subroutine finishes and control is handed back to the caller.

Even when a function calls itself recursively, the return address for each invocation must be stored separately — the call stack handles this automatically.

How It Works

The interactive diagram below shows how stack frames are pushed and popped as functions call and return.

Call stack animation with Python codeLeft: Python source code. Right: call stack frames animating as functions are called and returned. Code blocks and stack frames are synchronized.Python codedef main(): num = 42 result = calculate() print(result)main() # entry pointdef calculate(): x = 10 val = add(3, 4) return val + x# returns to maindef add(a, b): result = a + b return result# returns to calculateExecution order① call main()② main → calls calculate()③ calculate → calls add(3, 4)④ add returns 7⑤ calculate returns 17⑥ main prints 17 and exitsCall stack (memory)(unused stack space)PUSH ↓add(3, 4)args: a=3, b=4local: result=7return addr → calculatecalculate()local: x=10waiting for add(3, 4)return addr → mainmain()local: num=42waiting for calculate()return addr → OSSPSPSPPOPhighlowLegendmain()calculate()add()corresponds to

① Calling main() pushes the main frame

main calls calculate(), pushing the calculate frame

calculate calls add(3, 4), pushing the add frame

add returns 7 and exits — the add frame is popped

calculate returns 17 and exits — the calculate frame is popped

main prints 17 and exits — the main frame is popped, leaving the stack empty

References