C Programming

Lesson 11 of 11

Mark and Sweep GC

Mark-and-sweep takes a completely different approach from reference counting: instead of tracking counts continuously, it periodically pauses the program and asks one question directly, "starting from everything currently reachable, what's still alive?" Anything left over gets swept away.

It runs in two phases:

  1. Mark: starting from a set of "roots" (global variables, local variables currently on the stack), recursively visit every object reachable from them, flagging each one as marked.
  2. Sweep: walk every object the allocator has ever handed out, free any that weren't marked, then clear the marks for next time.
C

Notice markObject checks obj->marked before recursing, this is exactly what solves the cycle problem from the last lesson: two objects referencing each other both simply get marked once each, then correctly swept together if nothing external points to either.

The tradeoff

RefcountingMark and Sweep
Handles cyclesNoYes
OverheadA little, on every assignmentA pause during collection
SimplicitySimpler per-operationMore bookkeeping (roots, linked list of all objects)

Neither is strictly "better", refcounting is used where memory needs to be freed the instant it's unreachable (like Swift's ARC), mark-and-sweep is used where occasional pauses are acceptable in exchange for never leaking cycles (like most JavaScript engines).

Final project

Combine everything from this course: write a small C program with an Obj type (int and string, like the earlier lessons), a way to track "roots", and a working mark + sweep pair that correctly frees unreached objects, including a deliberate reference cycle to prove it doesn't leak. Submit a link to your repository below, an instructor will review it before you can mark this lesson complete.

This lesson ends in a project. Build it on your own machine, there's nowhere to submit it here, but the brief above is everything you need.

📝 Mark and Sweep GC Quiz

Passing score: 70%
  1. 1.What are the two phases of a mark-and-sweep collector?

  2. 2.Mark-and-sweep correctly frees a reference cycle that nothing external points to, unlike plain refcounting.

  3. 3.The starting points a mark-and-sweep collector walks from (globals, the current stack) are called ____.