Master the fundamental concepts of garbage collection through this focused micro-challenge.
Managed runtimes reclaim unreachable objects automatically. Mark-and-sweep: trace from roots (stack, globals), mark reachable objects, sweep unmarked objects back to the free list. Python's cyclic GC layers atop refcount; Go uses concurrent mark-sweep.
Mark: DFS/BFS from roots, set mark bit in object header. Sweep: walk heap, free unmarked objects, clear marks on survivors for next cycle.
cLoading…
Production compilers embed this step inside a longer pipeline. GCC flows through cpp, cc1, assembly, and ld; Clang uses the driver, Sema, LLVM IR passes, and a target backend. LLVM bitcode, JVM bytecode, and WASM are other familiar IRs at the same layer. The exercise isolates one pass so you can test it alone before chaining it to the next stage.
You will implement basic mark-and-sweep garbage collection. This exercise requires tracing from roots, marking reachable heap objects, and reclaiming unmarked memory in a sweep pass.
Implement a mark-and-sweep garbage collector over a simulated heap driven by a script: objects are allocated, linked to each other, and made reachable (or not) from roots; each collection marks everything reachable and frees the rest.
One command per line:
| Command | Meaning |
|---|---|
new NAME SIZE | allocate object NAME of SIZE bytes |
link A B | add a pointer from A to B (an object can point to many, in order) |
unlink A B | remove the pointer A → B (the first one, if repeated) |
root NAME / unroot NAME | add / remove a root (roots are kept in the order added) |
gc | run a collection |
Names are unique among live objects; a freed object's name may be reused by a later new.
For each gc, numbered from 1:
cLoading…
At the end: heap: NAME NAME ...: live objects in allocation order (or heap: empty).
Input:
cLoading…
Output:
cLoading…
Hidden tests cover shared children reached twice, several roots, and reuse of a freed name.
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
Every task includes starter code, theory, and hidden tests so you can implement and verify locally in the browser.
How it works