A minimal mark-and-sweep garbage collector implementation in C.
MiniGC is an educational implementation of a simple garbage collector that uses the mark-and-sweep algorithm. It demonstrates fundamental GC concepts including object allocation, reachability analysis, and automatic memory reclamation.
- Mark-and-Sweep Algorithm: Implements the classic two-phase garbage collection
- Stack-based VM: Uses a virtual machine with a stack to manage object references
- Two Object Types: Supports integers and pairs (cons cells)
- Cycle Detection: Handles circular references without infinite loops
- Dynamic Threshold: Automatically adjusts GC trigger threshold based on live objects
- Mark Phase: Traverses all reachable objects from the stack and marks them as alive
- Sweep Phase: Reclaims memory from unmarked (dead) objects and resets marks for the next cycle
- Automatic Triggering: GC runs when the number of objects reaches a threshold
gcc main.c -o minigc
./minigcThe program includes four test cases:
- Test 1: Objects on stack are preserved
- Test 2: Dead objects are collected
- Test 3: Nested objects are reached
- Test 4: Circular references are handled correctly
- Initial threshold: 8 objects
- Stack capacity: 256 objects
- Threshold adjustment: Doubles after each GC cycle (or resets to 8 if no objects remain)
This project is designed for learning purposes to understand:
- How garbage collectors work
- Memory management in programming languages
- The mark-and-sweep algorithm
- Handling object graphs and cycles