Crafting Interpreters · Week 24
Ch 26: Garbage Collection
Updated
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.
See it
All visualsStep through at your own pace; the arrow keys work too.
Gray stack
- 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 stepsEnable the stress-GC mode (collect on every allocation) and the GC log as the book suggests.
Write the code in your lox repo
Type it into clox/ (C) yourself as you read, and get it running.
Challenge 1 (shrink the object header) and challenge 2 (avoid clearing mark bits on every sweep) are good optimizations.
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 youSign 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 postsQuestions 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.