Who cleans up a program's memory?
Many programs never free their own memory: a hidden helper, invented around 1959 for Lisp, sweeps up what nobody uses.
▶ Start the storyIn many languages, a hidden helper called the garbage collector does it. A program keeps asking for memory to hold its data. Garbage collection is a form of automatic memory management: it reclaims memory that the program allocated but no longer references, and that leftover memory is called garbage. The idea was invented by John McCarthy around 1959 to simplify manual memory management in Lisp, where the programmer has to say which objects to release and when.
Doing that by hand goes wrong in two classic ways. A appears when memory is freed while pointers to it remain; if one is used, the memory may already have been reassigned to something else, with unpredictable results. A is the opposite mistake: the program fails to free memory held by objects it can no longer reach, which can eventually lead to memory exhaustion.
Collectors find garbage in two main ways. Tracing collectors start from certain , follow chains of references to see what is still reachable, and treat the rest as garbage. gives every object a tally of the references to it, and when the tally reaches zero its memory is reclaimed. Counting has a weak spot: objects that refer to each other form a cycle whose counts never reach zero. Some systems, like CPython, add cycle-detecting algorithms to cope.
Step 1: Tracing
Start at the roots, follow every reference, keep what you reach
Step 2: Everything unreached is garbage
Its memory is reclaimed
Step 3:
Each object counts the references pointing to it
Step 4: Count hits zero
The object's memory is reclaimed at once
The convenience has a price. The collector uses computing resources to decide what to free, and it can run at unpredictable moments, causing stalls that real-time and interactive programs may not accept. For that reason iOS never adopted garbage collection and uses automatic instead, and C and C++ were designed for manual memory management.
Quiz me
0/3
Recap
Memory is either cleaned up by the programmer, or by a collector that trades some speed and predictability for safety.
💡 A trick to remember it · Tracing walks the room to find what's used; counting asks every plate how many hands still hold it.
Surprising fact · Pure reference counting cannot free objects that refer to each other in a cycle.
Connects to
- 🔧 How did Grace Hopper's compiler teach computers to read words?
- 🛡️ Why is the US government telling programmers to move away from C?
- 🐍 Why are AI agents mostly built in Python and TypeScript, and where do you start?
- 🗃️ Why does a processor keep a tiny memory right next to itself?
- 🧮 Why can you only keep a few things in mind at once?
- Programming language
- Interpreter computing
Sources (1)
No source, no claim. Every fact in this lesson (16 claims) cites at least one of these.