How garbage collection (mark and sweep) works
Start from the things your program can reach, mark everything they touch, then sweep away whatever was never marked. Each step is one object.
Tweak it
Break it
Normal run: mark from every root, then free only the unmarked objects.
What to notice
- Roots are where the program can start from: stack variables, globals. An object is live if you can follow references from a root to it.
- Mark: white = not seen yet, amber = found but its references not scanned yet, blue = scanned. When no amber is left, every reachable object is blue.
- Sweep: walk the heap and free every object that is still white. Garbage can even point at other garbage, or in a cycle, and still gets collected.
- Raise References per object: denser graphs mean more of the heap is reachable, so less is freed.
- Break it: miss one root and the collector frees objects the program still uses. The red ones are dangling pointers, the root of use-after-free crashes.
- Real collectors add tricks (generations, incremental or concurrent marking, write barriers) that are not shown here.