Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Simple Garbage Collector

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.

Usage

#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)

API

Alloc

void* gc_alloc(size_t size);

Realloc

void* gc_realloc(void* ptr, size_t size);

Free

Totally optional

void gc_free(void* ptr);

Manual Garbage Collection Trigger

void gc_collect();

Debugging

Enable debug logging at compile time:

-DGC_DEBUG

Prints allocation, root discovery, marking, and sweeping details to stderr.

Drawbacks

This project makes many unsafe assumptions. These are not bugs.

Compiler optimizations

  • Dead pointers may be removed entirely
  • Inlining changes stack layout
  • -O2 and -O3 will break root discovery

Toolchain Restrictions

  • Uses GCC/Clang features
  • Will break under MSVC

Stack boundary detection

  • Incorrect stack top or bottom detection can crash or leak
  • Running the GC outside of main without a wrapper can break scanning

Threads

  • Completely unsupported
  • Other threads may mutate the heap during collection
  • No synchronization of any kind

Mixing memory models

  • Mixing GC-managed memory with malloc or free is undefined behavior
  • Freeing GC memory manually will corrupt the heap

About

Simple Garbage Collector for C

Topics

Resources

Stars

Watchers

Forks

Contributors

Languages