Master the fundamental concepts of build a bytecode vm through this focused micro-challenge.
Heap objects outlive stack slots. Mark-and-sweep finds unreachable objects by graph traversal from roots, then frees everything unmarked. Lua's collector and CPython's cycle-breaking GC both extend this family of algorithms.
Every heap object carries a mark bit. Collection runs in two passes:
Roots are anything the running program can still reach without loading from the heap. Missing a root means collecting live data; scanning too much means extra pause time.
For example, allocate three string objects, drop two references, run GC, and only the still-referenced string survives.
```c void collect_garbage() { mark_roots(); sweep(); } ```
Trigger collection when allocation fails or crosses a threshold. Print heap stats before and after to see bytes reclaimed.
Treat the operand stack, every frame's locals, and any global roots as scan starting points. Missing one root frees live objects; scanning too much only costs time. Log object counts before and after collection to verify unreachable nodes actually disappear.
This exercise asks you to add a mark-and-sweep collector to your object-allocating VM. You will implement `mark_roots`, recursive `mark_object`, and `sweep` over an allocation linked list.
Add a mark-and-sweep garbage collector to your VM in C.
Requirements:
Test:
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
All starter code and reference implementations are available for your local setup.
View on Github