Project 1: The Manual Reference Counter
A smart-pointer-like system in C where you wrap allocations in a struct that tracks how many “owners” it has. When the count hits zero, it automatically calls
free().
Quick Reference
| Attribute | Value |
|---|---|
| Primary Language | C |
| Alternative Languages | C++, Rust (raw pointers) |
| Difficulty | Level 2: Intermediate |
| Time Estimate | See main guide |
| Knowledge Area | Memory Management / Pointers |
| Tooling | malloc/free |
| Prerequisites | See main guide |
What You Will Build
A smart-pointer-like system in C where you wrap allocations in a struct that tracks how many “owners” it has. When the count hits zero, it automatically calls free().
Why It Matters
This project builds core skills that appear repeatedly in real-world systems and tooling.
Core Challenges
- Tracking increments/decrements → maps to Reference Counting overhead
- Handling circular refs (The Leak) → maps to Why we need Mark-and-Sweep
- Thread safety → maps to Atomic increments vs. Performance
Key Concepts
- Reference Counting: “The Garbage Collection Handbook” Ch. 5 - Richard Jones
- Atomic Operations: “C Programming: A Modern Approach” - K.N. King
Real-World Outcome
REF(Person) p = ref_new(Person);
ref_inc(p); // Count 1
{
REF(Person) alias = p;
ref_inc(alias); // Count 2
}
ref_dec(p); // Count 1
// ... later ...
ref_dec(p); // Count 0 -> memory freed!
Implementation Guide
- Reproduce the simplest happy-path scenario.
- Build the smallest working version of the core feature.
- Add input validation and error handling.
- Add instrumentation/logging to confirm behavior.
- Refactor into clean modules with tests.
Milestones
- Milestone 1: Minimal working program that runs end-to-end.
- Milestone 2: Correct outputs for typical inputs.
- Milestone 3: Robust handling of edge cases.
- Milestone 4: Clean structure and documented usage.
Validation Checklist
- Output matches the real-world outcome example
- Handles invalid inputs safely
- Provides clear errors and exit codes
- Repeatable results across runs
References
- Main guide:
LEARN_MODERN_GC_DEEP_DIVE.md - “The C Programming Language” by K&R