r/C_Programming • u/Upbeat-Aioli-3634 • Jul 13 '26
Project I added a mark-and-sweep garbage collector to my programming language written in C
I’ve been building a Python-like interpreted language called Nearoh from scratch in C.
Until recently, the runtime could execute functions, classes, lists, dictionaries, imports, file I/O, loops, and other basic language features, but its ownership model was becoming a serious limitation.
Over the latest development session, I rebuilt the relevant parts of the runtime around a non-moving mark-and-sweep garbage collector.
The runtime now supports:
Garbage-collected heap objects
Heap-allocated lexical environments
Closures that can outlive their defining function
Shared identity for mutable lists, dictionaries, and instances
Recursive object graphs
Cycle-safe printing
Collection under both normal thresholds and an aggressive stress mode
The GC implementation is currently around 384 lines of C. The whole repository is 11,713 lines across 120 files, including a lexer, parser, AST, evaluator/runtime, built-ins, module system, diagnostics, tests, and a native Win32/GDI IDE.
One of the bugs this fixed involved escaped closures. Previously, a function could retain a reference to an environment whose lifetime was tied too closely to the original call. Environments are now heap objects traced by the collector, so this works correctly:
def make_counter():
count = 0
def increment():
count = count + 1
return count
return increment
The other major correction involved mutable values. Assigning a list or instance to another variable now preserves object identity instead of creating accidental value-like behavior.
I also added cycle handling so recursive containers no longer cause infinite recursion while being printed.
The complete regression suite currently passes with both ordinary threshold-based collection and GC stress mode enabled.
I’m still learning a lot while building this, so I’d be interested in feedback on the collector architecture, object representation, root tracing, and anything obviously dangerous or unidiomatic in the C implementation.
Repository:
https://github.com/ReeceGilbert/Nearoh-Coding-Language