Sub topic 1
How a Program Uses Memory: Stack and Heap
Prerequisites
This chapter assumes you can read basic Python, know what a list and a function call are, and have seen Big O notation for time complexity. No earlier knowledge of memory layout is needed.
Why memory layout matters
Space complexity counts how much memory an algorithm needs as its input grows. To count memory, you first need to know where a program keeps its data. Most languages use two regions: the call stack and the heap.
The call stack
The call stack holds one frame for each function call that is still running. A frame stores the function's local variables, its arguments, and the place to return to when the function ends.
Frames follow a last-in, first-out rule. A new call adds a frame on top. When that call returns, its frame is removed. The caller's frame becomes the top again.
Stack memory is managed for you. It is freed automatically when a function returns. It is also limited in size. In Python, the default recursion limit is about 1000 frames, and going past it raises RecursionError.
The heap
The heap is a large pool of memory for objects whose size or lifetime is not fixed by the call structure. Lists, dictionaries, strings, and instances of classes live there. An object stays alive as long as something refers to it. Python frees it once no references remain.
In Python, a local variable is a name stored in the frame that points to an object on the heap. The frame holds the reference. The heap holds the data.
def build(n):
items = []
for i in range(n):
items.append(i)
return items
data = build(5)While build runs, its frame holds n, i, and the name items. The list itself sits on the heap and grows as items are appended. When build returns, its frame is removed, but the list survives because data still refers to it.
Where each cost shows up
Space complexity adds up both regions. The two sources of memory differ in what makes them grow.
| Region | What it holds | What makes it grow |
|---|---|---|
| Stack | Frames for active calls | Recursion depth |
| Heap | Lists, dicts, strings, objects | Amount of data you create |
A loop that appends n items grows the heap. A function that calls itself n times deep grows the stack. Both give O(n) space, but the cause differs, and so does the fix.
def count_down(n):
if n == 0:
return 0
return count_down(n - 1)count_down creates no list, yet it keeps n + 1 frames alive at the deepest point. Its stack use is O(n).
Common mistakes
- Counting only the heap. Recursive functions use stack space even when they allocate nothing.
- Assuming a returned object disappears with its frame. Only the frame is freed. The object stays alive while a reference exists.
- Treating the stack limit as unlimited. Deep recursion can fail with
RecursionErrorlong before memory runs out.
Exercise
A function takes a list of n numbers and returns the sum using a for loop and one variable. Another function builds a new list of n squares. For each, say whether the memory grows on the stack or the heap, and give the auxiliary space in Big O.
Show answer
The sum function uses only a few local names in one frame, so its stack and heap use are constant: O(1). The squares function grows the heap with a new list of n items, so its auxiliary space is O(n). Its stack stays at one frame.
Exercise
A recursive function calls itself once per element of a list of length n and creates no lists. Which region grows, and how much?
Show answer
The stack grows. Each call leaves a frame alive until the deeper call returns, so there are about n frames at the deepest point. The auxiliary space is O(n).