Module 6 · Intermediate · Inside the hardware: from transistors to processors

Stack and heap memory explained

Stack vs heap memory: how a program lays out RAM, call frames and local variables, dynamic allocation, stack overflow, memory leaks, and how Python uses both.

By theprogrammers team · · 11 min read

Write a recursive function without a base case and Python stops with RecursionError: maximum recursion depth exceeded. In C, the same mistake crashes with "stack overflow", the error that gave a famous programming website its name. Load a huge dataset into a list and you might instead see MemoryError. These are two different parts of a program's memory running out: the stack and the heap.

When the operating system starts your program, it gives it a section of RAM and divides it into areas with different jobs. The stack holds function calls and their local variables, and is managed automatically and very quickly. The heap holds data that's created while the program runs and may outlive the function that made it. This lesson explains stack and heap memory: what goes where, why each exists, the bugs each causes, and how Python uses them.

What you need first: how RAM, hard disks and SSDs store data and Python functions. Assembly language helps with the push, pop and call instructions.

Key terms

  • Stack: an area of memory that grows and shrinks as functions are called and return, last in, first out.
  • Stack frame (call frame): the block of stack memory for one function call: its local variables, arguments and return address.
  • Heap: a large area of memory for data created at run time, in any order, that lives until it's freed.
  • Allocation: reserving a piece of memory; freeing (deallocation) gives it back.
  • Stack overflow: the stack runs out of space, usually from recursion that's too deep.
  • Memory leak: heap memory that's no longer needed but is never freed, so the program's memory keeps growing.
  • Garbage collector: part of a language's runtime that frees heap memory nothing refers to any more.

How a program's memory is laid out

Each running program (process) sees its own memory, divided roughly like this:

 high addresses
 ┌───────────────────────┐
 │ Stack                 │  function calls; grows downwards
 │          ↓            │
 │                       │
 │          ↑            │
 │ Heap                  │  data created at run time; grows upwards
 ├───────────────────────┤
 │ Global / static data  │  global variables, constants
 ├───────────────────────┤
 │ Code (text)           │  the program's machine instructions
 └───────────────────────┘
 low addresses
AreaHoldsSize
CodeThe machine instructionsFixed when the program loads
Global/static dataGlobal variables, string constantsFixed when the program loads
HeapObjects created while running: lists, strings, class instancesGrows as needed, up to available memory
StackOne frame per active function callSmall and limited, often 1 MB per thread on Windows and 8 MB on Linux by default

The stack and heap grow towards each other into the free space between them. Each thread (see threads and multitasking) gets its own stack; all threads share one heap.

The stack: function calls

Think of a stack of plates in a canteen. You can only add a plate on top or take the top one off: last in, first out (LIFO). The call stack works the same way.

When a function is called, a frame is pushed onto the stack. It holds:

  • the function's arguments and local variables,
  • the return address: where to continue in the caller when this function finishes,
  • some saved register values.

When the function returns, its frame is popped off, and all its local variables disappear in one go. At the machine level, this is one register, the stack pointer, moving up or down, which is why the stack is so fast: no searching, no bookkeeping.

You can watch frames being created and removed in Python:

def countdown(n, level=0):
    indent = "  " * level
    print(f"{indent}countdown({n}) starts: frame pushed")
    if n > 0:
        countdown(n - 1, level + 1)
    print(f"{indent}countdown({n}) ends: frame popped")

countdown(2)
countdown(2) starts: frame pushed
  countdown(1) starts: frame pushed
    countdown(0) starts: frame pushed
    countdown(0) ends: frame popped
  countdown(1) ends: frame popped
countdown(2) ends: frame popped

The last call to start is the first to finish: LIFO. Each call has its own n, because each has its own frame.

A Python traceback is a printout of the call stack at the moment of an error, oldest call at the top and the failing call at the bottom. Reading tracebacks is reading the stack; Python error messages shows how.

Stack overflow

The stack is small and fixed. Recursion that goes too deep keeps pushing frames until it runs out. Python protects you with a limit on how deep calls can go:

import sys

print(sys.getrecursionlimit())

def forever(n):
    return forever(n + 1)

try:
    forever(0)
except RecursionError as error:
    print("RecursionError:", error)
1000
RecursionError: maximum recursion depth exceeded

The default limit is 1,000 frames. Python stops you there and raises an exception you can catch, instead of letting the real stack overflow and crash the program. In C or C++, there's no such guard: deep recursion overwrites memory past the stack's end and the program crashes with a segmentation fault or "stack overflow". The fix is almost always a missing or wrong base case, or rewriting deep recursion as a loop; see recursion in Python.

The heap: data that outlives a call

Local variables vanish when their function returns. But programs constantly create data whose lifetime doesn't match one function call: a list of a million rows loaded from a file, a user's shopping cart, a web page being built. That data goes on the heap.

Heap memory is allocated on request and stays until it's freed, in any order. That flexibility costs time: the memory allocator has to find a free piece of the right size, keep track of what's used, and handle freeing. It's slower than the stack, and the free space can become fragmented into small gaps between used pieces.

Who frees heap memory depends on the language:

LanguageAllocateFree
Cmalloc(size)free(pointer), by hand
C++newdelete, by hand, or automatically with smart pointers
RustBox::new, VecAutomatically when the owner goes out of scope, checked by the compiler
Python, Java, JavaScript, Go, C#Just create objectsA garbage collector frees what nothing refers to

Manual freeing causes two classic bugs:

  • Memory leak: forgetting to free memory. The program's memory use climbs until it slows down or is killed.
  • Use after free / double free: using or freeing memory that's already been freed. These cause crashes and are a major source of security vulnerabilities.

Garbage-collected languages avoid both, at the cost of some extra work while the program runs.

Stack vs heap at a glance

StackHeap
HoldsFunction frames: locals, arguments, return addressesObjects created at run time
OrderLast in, first outAny order
Managed byAutomatically, by function calls and returnsThe allocator, plus you or a garbage collector
SpeedVery fast (move one pointer)Slower (find space, track it)
SizeSmall, fixed per thread (MBs)Large, up to available RAM
LifetimeUntil the function returnsUntil freed or garbage-collected
Typical errorStack overflow / RecursionErrorMemory leak, MemoryError, fragmentation
Shared between threads?No, each thread has its ownYes

How Python uses the stack and heap

In Python, every object lives on the heap: numbers, strings, lists, dictionaries, your own class instances. Variables are names that refer to objects. When a function runs, its frame holds those names (its local variables), and the names point to objects on the heap.

That's why a function can change a list passed into it, and why an object can outlive the function that created it:

def add_mark(marks):
    marks.append(90)          # changes the list object on the heap

def make_list():
    data = [1, 2, 3]          # the list is created on the heap
    return data               # the name 'data' disappears with the frame, the list doesn't

my_marks = [72, 85]
add_mark(my_marks)
print(my_marks)

result = make_list()
print(result)
[72, 85, 90]
[1, 2, 3]

marks and my_marks are two names, in two different frames, for the same list object on the heap. When make_list returns, its frame and the name data are gone, but the list survives because result now refers to it.

Python frees objects automatically:

  1. Reference counting: every object counts how many references point to it. When the count drops to zero, it's freed immediately.
  2. A cycle collector (the gc module) finds groups of objects that refer only to each other, like two objects pointing at each other, and frees those too.

Python can still "leak" memory in a practical sense: if you keep adding to a global list or dictionary and never remove anything, nothing becomes garbage, so memory grows. Caches that grow without a limit are the usual culprit.

Practice

  1. A function f calls g, which calls h. Which frame is popped first, and what does the stack look like while h runs?
Show the answer

h's frame is popped first, because it was pushed last. While h runs, the stack has (from bottom to top) the main program, f, g and h.

  1. Which area of memory, stack or heap, holds each: a local loop counter in a C function; a 500 MB array loaded from a file; the return address of a function call?
Show the answer

The loop counter: stack. The 500 MB array: heap (it's far too big for the stack, and may need to outlive the function). The return address: stack.

  1. Why is the stack faster than the heap?
Show the answer

Allocating on the stack is just moving the stack pointer, and all of a frame's memory is freed at once when the function returns. The heap needs an allocator to find a free block of the right size and track it, and something (you or a garbage collector) must free each object.

  1. What does this print, and why?
def reset(items):
    items = []

numbers = [1, 2, 3]
reset(numbers)
print(numbers)
Show the answer
[1, 2, 3]

items = [] only makes the local name items (in reset's frame) point to a new empty list. The original list on the heap, which numbers still refers to, is unchanged. items.clear() would have emptied it.

  1. A server's memory use grows by 50 MB every hour until it crashes, but there are no errors in the code. What's a likely cause in a Python program?
Show the answer

Something keeps references to objects it no longer needs, so they're never freed: a global list or dictionary that's only ever added to, such as a cache with no size limit or a log of every request. Fix it by limiting the cache (for example with functools.lru_cache(maxsize=...)) or removing old entries.

Interview questions

What is the difference between stack and heap memory?

The stack stores function call frames (local variables, parameters, return addresses), is allocated and freed automatically in LIFO order by moving the stack pointer, is very fast, small and per-thread. The heap stores dynamically allocated objects with arbitrary lifetimes, is managed by an allocator and freed manually or by garbage collection, is larger, slower, shared by threads and can fragment.

What causes a stack overflow?

Using more stack space than the thread was given, almost always through unbounded or very deep recursion, or occasionally very large local arrays. Each call pushes a frame; without returning, frames accumulate until the stack's limit is hit.

How does Python manage memory?

All objects live on a private heap managed by the interpreter. CPython frees objects mainly by reference counting, as soon as their count reaches zero, and runs a cyclic garbage collector to reclaim reference cycles. Small objects come from a specialised allocator (pymalloc) to reduce fragmentation and overhead.

Key takeaways

  • A running program's memory has code, global data, a heap and a stack.
  • The stack holds one frame per function call (locals, arguments, return address), works last in first out, and is fast but small.
  • Too-deep recursion overflows the stack; Python stops at 1,000 frames by default with RecursionError.
  • The heap holds data created at run time that can outlive a function; it's bigger but slower, and must be freed by you or a garbage collector.
  • In Python, every object is on the heap, variables in each frame refer to them, and reference counting plus a cycle collector free them.

Frequently asked questions

Is the stack in RAM?

Yes. Both the stack and the heap are regions of the same RAM, given to the process by the operating system. The difference is how each region is organised and managed, not the hardware.

Should I increase Python's recursion limit?

Rarely. sys.setrecursionlimit() can raise it, but the real stack underneath is still limited, and a very high limit can crash Python outright. If you need deep recursion, rewrite the function as a loop, or use an explicit list as your own stack.

Does Python have memory leaks?

Not in the C sense, since unreferenced objects are freed automatically. But a program leaks memory in practice if it keeps references it no longer needs, such as an ever-growing list, dictionary or cache.

What to learn next

  1. See how each thread gets its own stack in threads, multithreading and multitasking.
  2. Practise recursion safely with recursion in Python.
  3. Find out where a program spends its time in CPU profiling.