orangeduck/tgc
FreeA Tiny Garbage Collector for C
About orangeduck/tgc
tgc is a tiny garbage collector for C, written in approximately 500 lines of code. It implements a conservative, thread-local, mark-and-sweep garbage collector that automatically frees memory allocated via tgc_alloc and related functions once it becomes unreachable. The library supports destructors, manual freeing, pausing and resuming the collector, and provides functions like tgc_calloc, tgc_realloc, and tgc_alloc_opt. Reachability is determined by pointers on the stack or in other tgc-allocated memory, with specific limitations (e.g., pointers must point to the start of an allocation; pointers from static data, malloc'd memory, or other threads do not keep allocations alive). It is based on the Cello Garbage Collector and is suitable for C programs that want automatic memory management without a heavy dependency.
Key Features
Pros & Cons
- Very small codebase (~500 lines) making it easy to understand and audit
- Simple API with only a few functions
- Automatic memory management reduces risk of memory leaks and dangling pointers
- Thread-local design avoids locking overhead in single-threaded or per-thread contexts
- Supports destructors for cleanup when memory is freed
- Open source and permissively licensed
- Not thread-safe across threads (thread-local only – each thread must start its own collector)
- Conservative collector may have false positives (keep memory alive unnecessarily)
- Reachability limitations: pointers must point exactly to the start of an allocation; pointers from static data, malloc'd memory, or other threads do not prevent collection
- Only works with memory allocated via tgc_alloc family – mixing with malloc/calloc/realloc can lead to issues
- No support for weak references or finalization ordering beyond destructors