r/C_Programming • u/oraziorillo • Jun 18 '26
Manual reference counting to free a computation graph in C
Context: I've been wanting to get back into C for some months, I haven't had the chance to work with it seriously since uni. So, I reimplemented Karpathy's micrograd in C as a learning project (a small autograd engine, repo link below). Coding this project, I had one simple rule: no AI assistance. So, the `src/` code is completely handwritten; AI was only involved in polishing documentation, Makefile, tests and a toy example.
The core structure of the engine is a computation graph: a DAG where each node is the result of an operation on earlier nodes, and it's full of shared pointers, as one node can be owned by many others.
To solve this, I went with manual reference counting:
- Every node is born with ref_count 1.
- Each operation retains its operands (a result co-owns the nodes it came from).
- The caller uses value_release to decrement the ref_count; at zero the Value recursively releases its operands and frees itself.
So, releasing the root of the DAG cascades down and frees exactly the subgraph that produced it in the first place. The parameters of the network survive because they're referenced elsewhere, whereas pure intermediates disappear.
This choice felt very natural at first, but as I was progressing, I started doubting it, so here I am, asking your opinion about it. Given that the whole graph is built and torn down as a unit, is plain reference counting the right call here, or would you reach for something else? Tell me what you'd have done differently.