Course outline · 0% complete

0/28 lessons0%

Course overview →

Garbage collection, gently

lesson 4-3 · ~10 min · 13/28

Who cleans up the heap?

In lesson 4-1 you saw that heap objects live "as long as anything points at them". Someone has to notice when nothing points at an object anymore and reclaim that memory. In C, that someone is you (malloc/free, and forgetting is a leak). In Python, Java, JavaScript, and Go, it is the garbage collector (GC).

Python's main strategy is reference counting: every object carries a count of how many references (arrows) point at it. Assignment adds one, deleting a name or a name going out of scope removes one. The moment the count hits zero, the object is freed immediately.

We can watch this happen using __del__, a method Python calls right when an object is being freed.

Code exercise · python

Run this and check the ORDER of the lines. The object survives del r because s still points at it. It is freed the instant the last reference disappears.

Code exercise · python

Your turn. Create Resource "B", put it in a list called box, then delete the name r. Print "still alive inside the list". Then empty the list with box.clear() and print "after the list let go". Match the expected order exactly.

What this means for your code

  • Leaks still happen in GC languages. The GC only frees unreachable objects. A global list or cache that keeps growing keeps everything in it reachable forever. That is the slow-OOM pattern from lesson 4-2.
  • Reference counting has one blind spot: cycles. If A points to B and B points to A, their counts never reach zero even when nothing else can reach them. Python runs a second, occasional cycle collector to catch these.
  • GC costs CPU time. That is the trade: C is fast and manual, Python is safe and pays a tax. For most software the safety is worth it.

Quiz

A Python service stores every request it has ever seen in a module-level list for "debugging". Memory grows forever. Why does the garbage collector not fix this?