Mental model
A program can only use an object if it can reach it. The starting points are the roots: local variables of calls that are still running, static fields, and a few runtime-internal references. Follow every reference from the roots, and from what they reach, and so on: everything you can get to is live. Everything else is garbage, because no code can ever touch it again, so its memory can be reused.
Reachability, not "is anyone pointing at it", is the rule. Two objects that refer only to each other are garbage if nothing reachable refers to either.
Mark and sweep
The lab runs the textbook tracing algorithm on a small object graph:
- Mark: push every root's object on a work stack and mark it. Repeatedly pop an object and scan its references; mark and push each target not marked yet. An already-marked target is skipped, which is what makes cycles terminate.
- Sweep: walk all objects; unmarked ones are garbage and their memory is reclaimed.
Marking visits each live object and each of its references once: O(live objects + references). Sweeping touches every object in the heap.
Production collectors are far more refined. The .NET GC and the HotSpot collectors are generational (most objects die young, so young objects are collected often and cheaply), they usually compact live objects to remove fragmentation, and several do much of their work concurrently with the program. The rule they implement is still reachability, and they choose when to run. You cannot predict the moment an unreachable object's memory is reclaimed.
Reference counting and cycles
Another strategy keeps a count of references to each object and frees it the moment the count drops to zero. Freeing is immediate and predictable, but a cycle keeps every count above zero forever.
- CPython uses reference counting for most objects, so non-cyclic garbage is freed at once. A
separate cycle collector (the
gcmodule) periodically finds groups of objects that are only reachable from each other and frees them. In the lab's Python rules, the sweep says which garbage reference counting would already have freed and which needed the cycle collector. - C++
std::shared_ptris reference counting without any cycle collector. Two objects holdingshared_ptrs to each other are never freed: a leak. Make one direction astd::weak_ptr, which observes without owning. In the lab's C++ rules, unreachable cycles are shown as leaked.
Deterministic cleanup is a separate job
Memory is one resource among many. Files, sockets, locks and database connections must be released at a known point, not "eventually". Every language has a construct that runs cleanup when a scope ends, including when an exception leaves it:
| Language | Construct | What runs |
|---|---|---|
| C# | using statement or using var declaration |
Dispose() |
| Java | try-with-resources | close() (of AutoCloseable), in reverse order |
| Python | with statement |
the context manager's __exit__() |
| C++ | any object with automatic storage (RAII) | its destructor, in reverse order of construction |
In C#, Java and Python, cleanup and memory reclamation are separate events: after Dispose, close
or __exit__, the object itself is still an ordinary object until it becomes unreachable. In C++
they coincide: the destructor runs and the storage is released at the end of the scope. Turn on the
lab's scoped resource to see the difference.
Avoid relying on finalizers for cleanup. C# finalizers run on the collector's schedule, possibly
never before the process exits; Java's finalize is deprecated for removal (use Cleaner as a
safety net, try-with-resources as the real mechanism); Python's __del__ runs when CPython's count
reaches zero but later, or not at all, on other implementations.
Common mistakes
- Expecting the garbage collector to close files promptly.
- Assuming an object is freed "when the method ends" in C# or Java.
- Building parent ↔ child links with
shared_ptrin both directions. - Keeping a long-lived reference (a static cache, an event subscription) to objects you think are garbage: they are reachable, so they are not collected. That is how leaks happen in GC languages.
Edge cases
- No roots: everything is garbage.
- A self-reference (
A → A) does not keepAalive in a tracing collector. - Garbage that a cycle points to (but which is not itself in the cycle) is also stuck under pure reference counting until the cycle is broken.
Worked practice
1. Objects A, B, C, D; references A→B, C→D, D→C; root A. Which are garbage? What happens to them in CPython, and with shared_ptr links in C++?
Answer
C and D are garbage (only they refer to each other). In CPython their reference counts stay at 1,
so the cycle collector frees them. With shared_ptr in both directions they leak.
2. Why does marking terminate on a graph with cycles?
Answer
Each object is pushed only when it is first marked, and a marked object is never pushed again. So each object is scanned at most once, and the work stack eventually empties.
Summary
- Live means reachable from a root; everything else is garbage.
- Tracing collectors mark from the roots and reclaim the rest, cycles included, at a time they choose.
- Reference counting frees immediately but misses cycles: CPython adds a cycle collector,
shared_ptrneedsweak_ptr. - Release resources deterministically with
using, try-with-resources,withor RAII.