1def make_box(w, h):2 box = [w, h]3 return box45b = make_box(3, 4)6del bPythoncall stackmain programmake_box(3, 4)↩ line 5f()calls f() againf()calls f() againf()calls f() againheap3int4intlist[,]1int *p = malloc(8);2free(p);C8 bytesRecursionError
Code cards: the Python program and two lines of C; the highlighted line is the one the step is aboutCall stack: one block per running call, newest on top, showing its namesHeap: one block per object; the dashed outlines are free roomWires: a name (or a list slot) refers to the object at the arrowheadEach running call has a frame on the call stack holding its names; each value is an object on the heap, and a name holds a reference (a wire) to it. A call drops a frame on the pile; return lifts it off, but an object it made stays on the heap while anything still refers to it, and is freed when nothing does. Runaway recursion piles frames up until Python raises a RecursionError (limit 1000 by default). In C you take heap memory with malloc and must hand it back with free. The drawing shows one block per running call. In CPython each call gets a frame; frame.f_back links it to the caller’s frame, which remembers where it paused. In machine code, as compiled from C, the call itself pushes a return address on the stack.

Frames

  1. Line 5 calls make_box(3, 4). Python pushes a new frame onto the call stack: scratch space for this one call. It holds the parameters w and h, room for local variables, and where to go back to: line 5.

Objects on the heap

Freeing and limits

C by hand

Try it

;; step 1/9 · line 5: b = make_box(3, 4)
>>> def make_box(w, h):
...     box = [w, h]
...     return box
...
>>> b = make_box(3, 4)
>>> b
[3, 4]

The drawing shows one block per running call. In CPython each call gets a frame; frame.f_back links it to the caller’s frame, which remembers where it paused. In machine code, as compiled from C, the call itself pushes a return address on the stack. CPython makes small ints, from -5 to 256, once and shares them, so the 3 and 4 already exist before the call.