A small experimental conservative garbage collector with stack scanning written in C.
This project is meant to explore how a garbage collector can be implemented from scratch in plain C without compiler or runtime support.
WARNING
THIS PROJECT IS NOT FOR PRODUCTION USE
This garbage collector is experimental and makes assumptions that will break under compiler optimization.
#define GC_DEBUG // for debug log
#include "gc.h"
int entry(int argc, char **argv) {
void *ptr = gc_alloc(10);
ptr = gc_realloc(ptr, 100);
// Remember to forget what a free() is ;)
}
GC_MAIN(entry)void* gc_alloc(size_t size);void* gc_realloc(void* ptr, size_t size);Totally optional
void gc_free(void* ptr);void gc_collect();Enable debug logging at compile time:
-DGC_DEBUG
Prints allocation, root discovery, marking, and sweeping details to stderr.
This project makes many unsafe assumptions. These are not bugs.
- Dead pointers may be removed entirely
- Inlining changes stack layout
- -O2 and -O3 will break root discovery
- Uses GCC/Clang features
- Will break under MSVC
- Incorrect stack top or bottom detection can crash or leak
- Running the GC outside of main without a wrapper can break scanning
- Completely unsupported
- Other threads may mutate the heap during collection
- No synchronization of any kind
- Mixing GC-managed memory with malloc or free is undefined behavior
- Freeing GC memory manually will corrupt the heap