Master the fundamental concepts of garbage collection through this focused micro-challenge.
Copying GC divides heap into from-space and to-space. Cheney's algorithm copies reachable objects to to-space, updates pointers, swaps spaces. Lisp machines and nursery collections in generational GC use copying for fast bump allocation. The tradeoff is memory: you need twice the heap capacity because only one semispace is active at a time.
Forward pointer scan iterates to-space. For each object, copy unforwarded children, leave forwarding pointer in from-space slot. Scan and free pointer chase each other through to-space until all reachable objects are copied.
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 copying garbage collection with semispaces. This exercise asks you to copy live objects, maintain forwarding pointers, and swap spaces after collection.
Implement a copying garbage collector with Cheney's algorithm: the heap is split into two semispaces; objects are allocated with a bump pointer, and a collection copies every live object into the other semispace, compacting it, and simply abandons everything left behind.
| Command | Meaning |
|---|---|
semispace BYTES | size of each semispace (first line) |
new NAME SIZE | allocate (sizes are multiples of 8) |
link A B / unlink A B | add / remove a pointer (ordered, like mark-and-sweep) |
root NAME / unroot NAME | roots, kept in the order added |
gc | collect now |
0x1000 and 0x2000. Allocation starts in the one at 0x1000.new bumps the allocation pointer. If the object doesn't fit in the rest of the current semispace, run a collection first (printed like any other); if it still doesn't fit, print out of memory: NAME and ignore that command.free = start of to-space. Copy each root, in root order, to free (skipping one already copied), advancing free by its size and leaving a forwarding address behind.scan = start of to-space. While scan < free: for the object at scan, copy each pointer target in link order (unless already forwarded), then advance scan past it.free in what was to-space.For each collection, numbered from 1:
cLoading…
At the end: heap: NAME@0xADDR ... in address order (or heap: empty).
Input:
cLoading…
Output:
cLoading…
Hidden tests cover shared objects copied once, cycles, a second collection back into the first semispace, and allocation that triggers a collection (and one that still fails).
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