Lesson 2 · Unit 02
Stack and heap
Two regions, two lifetimes
What you practise
- Call frames push and pop, heap objects outlive calls, who frees them (manual, reference counts, garbage collection), stack overflow and leaks
Try a question from this lesson
Pick one
A function finishes and returns. What happens to the memory that held its local variables?
Correct answer
It is released at once and reused by the next call
Why
Locals live in a block that exists only while the call runs. On return the block is dropped and the next call reuses the space. If locals stayed reserved, a long-running loop of calls would use up memory.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The stack
Each call pushes a frame onto the stack: its parameters, its locals, and where to return to. Returning pops it.
Only the top frame is running. The frames below are callers, paused mid-line. Pushing and popping is just moving one pointer, so the stack is very fast.
| g: n = 1 | <- top, running
| f: n = 2 | <- waiting for g
| main: x = 2 | <- waiting for f
+----------------+Concept
The heap
Data that must outlive the call that made it, or whose size is not known in advance, goes on the heap. You ask for a block and get back its address.
In Python every object lives on the heap. Stack frames only hold references to them.
stack heap
| make: nums --|---> [1, 2, 3]
| main: data --|---> (same list)9 more exercises in the app
- 1× type the answer
- 5× multiple choice
- 1× match the pairs
- 1× true or false
- 1× fill the blanks
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.