Crafting Interpreters · Week 24

Ch 26: Garbage Collection

Updated

About 8 hoursVerified by tests

Summary

Crafting Interpreters chapter 26, Garbage Collection: A mark-sweep garbage collector: roots, marking with a gray stack (tricolor abstraction), tracing references, sweeping unreachable objects, weak references for the string table, and when to trigger collection. Budget about 8 hours; the book's chap26_garbage tests check your code.

Flashcards 10 cards for Anki and AnkiMobile · all decks

Anki deck.tsv

Step through at your own pace; the arrow keys work too.

Crafting Interpreters · Ch 26 · TAOCP 2.3.5 Mark and sweep Gray objects wait on a stack to be traced; whatever is still white when marking ends gets swept away, cycles included.

Gray stack

  1. empty
  • white: not reached yet
  • gray: reached, references not traced
  • black: done

Pop C and blacken it: it references nothing new; the gray stack is empty, so marking is done.

This week's steps

4 steps
  1. Read the chapter

    Enable the stress-GC mode (collect on every allocation) and the GC log as the book suggests.

  2. Write the code in your lox repo

    Type it into clox/ (C) yourself as you read, and get it running.

  3. Do the challenges (1–3)

    Challenge 1 (shrink the object header) and challenge 2 (avoid clearing mark bits on every sweep) are good optimizations.

  4. Push and let the tests verify it

    Your repo runs the book's chap26_garbage tests on every push; passing marks this done.

Sign in to track this: tick each step off and it counts toward your week.

Your notes

Only you

Sign in to keep private notes on this guide, in Markdown. They stay yours: never on your profile, and you can export them all.

Discussion

0 posts

Questions about this chapter, tips, and what tripped you up. Hints over answers: full solutions go in a spoiler.

No posts yet. Ask a question or share a tip.

Sign in to postAnyone can read. Posting needs an account with a confirmed email.

Reference

Why it matters

GC is one of the most misunderstood parts of every runtime. After this, Java, Go and JavaScript GC logs make sense, and Knuth 2.3.5 will feel familiar.

How to approach it

Enable the stress-GC mode (collect on every allocation) and the GC log as the book suggests. Most bugs only show up under stress mode.

Challenges

3 challenges at the end of the chapter.

Challenge 1 (shrink the object header) and challenge 2 (avoid clearing mark bits on every sweep) are good optimizations. Challenge 3 (try another GC algorithm) is a big project; save it for after the book.

Common traps
  • An object allocated but not yet reachable gets collected mid-operation. Push temporaries on the stack before allocating again.
  • Forgetting to mark compiler roots while compiling.
  • Not removing unmarked strings from the intern table before sweeping.

Spot a mistake? Report it

Back to week 24