Building a Garbage Collector in C: Because Who Needs Sleep Anyway?

Let’s be honest: most people’s idea of a good time doesn’t involve poking around in the underbelly of C, trying to make memory management less… well, terrifying. But here I am, rolling up my sleeves and diving into the world of garbage collectors. Why? Because understanding how the engine works under the bonnet is way more fun than actually driving the car. (And also, I’m only a little cracked—not batshit crazy, so no assembly for now.)
Why C? Why Not?
You might ask, “Why C? Why not something friendlier, like Python, or at least C++ with its fancy destructors?” Well, I want to keep things low-level. Real low. Like, “I can see the bits and bytes from here” low. Plus, C gives you the delightful opportunity to shoot yourself in the foot with malloc and free, which is basically a rite of passage for any programmer.
Step 1: Accept Your Fate
Before you even write a line of code, accept that you will spend hours debugging segfaults, chasing dangling pointers, and questioning your life choices. This is normal. This is growth. This is C.
Step 2: Plan Your Collector
There are many flavours of garbage collectors—reference counting, mark-and-sweep, generational… I’ll probably start with something simple, like reference counting and end with mark-and-sweep, because I like the idea of pretending to be a janitor for my code. (“Sweep the heap, Daniel-san!”) And yes, I am only going to do 2 types.
Step 3: Write Some Code, Break Some Code
Here’s where the real fun begins. You’ll write a function to allocate memory, another to mark what’s still in use, and a third to sweep away the rest. Inevitably, you’ll forget to mark something, and your program will crash spectacularly. Don’t worry—it’s all part of the process.
Step 4: Document the Madness
As I go, I’ll document every step, every bug, and every existential crisis. Because if you can’t laugh at your own memory leaks, what can you laugh at?
The Journey Continues…
So, join me as I attempt to tame the wild beast that is manual memory management in C. Will I succeed? Will I lose my mind? Will I finally understand how the engine works beneath the bonnet? Only time—and a lot of printf debugging—will tell.
Stay tuned, and remember: in C, the real garbage collector… is you.
Subscribe to my newsletter
Read articles from Sunny directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
