Reference counts and cycles

Lesson 13 of 14 · C memory foundations

Reference counting tracks the number of owning references to an object. Choose a convention: a constructor returns one owned reference; retaining adds one; releasing removes one. When the count reaches zero, destroy the object and release the references it owns. A borrowed pointer does not by itself add a count and must not outlive the owner.

caller ──> A (count 1)
container ──> A (count 2)
caller releases   -> count 1
container releases -> count 0 -> destroy A

For a string object, destruction releases its owned character buffer and then the object. For a vector, it releases each owned component. An array destructor releases each owned element, then its pointer array, then the object. Replacing an element should retain the new object before releasing the old one: the two may be the same object, and releasing first could destroy it. After storing the new pointer, the old owned reference is gone. Check count overflow and prevent underflow; multithreaded updates require a suitable synchronization design.

Reference counting does not collect an isolated strong cycle:

external roots removed
A (count 1) ──> B (count 1)
      ^____________|

Each remaining count comes from the other object, so neither reaches zero despite being unreachable from the program’s roots. Weak references or a tracing collector can address cycles, but weak references require their own invalidation rules. Reference counting can reclaim promptly, yet each retain/release costs work and cascading destruction can take time. It does not automatically make all pointer use safe.

A complete single-edge reference-counted object

This deliberately small model uses one optional owned child rather than all the variants above. It demonstrates the accounting used by vector and array slots without relying on an external runtime.

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct Object Object;
struct Object { size_t refs; int value; Object *child; };

static Object *object_new(int value) {
    Object *o = malloc(sizeof *o);
    if (o) *o = (Object){.refs = 1, .value = value, .child = NULL};
    return o;
}

static bool retain(Object *o) {
    if (!o) return true;
    if (o->refs == SIZE_MAX) return false;
    ++o->refs;
    return true;
}

/* Requires a live owned reference, or NULL. */
static void release(Object *o) {
    if (!o) return;
    if (--o->refs == 0) {
        Object *child = o->child;
        printf("destroy %d\n", o->value);
        free(o);
        release(child);
    }
}

/* parent is live; child is NULL or live. Parent retains child. */
static bool set_child(Object *parent, Object *child) {
    if (!retain(child)) return false;
    Object *old = parent->child;
    parent->child = child;
    release(old);
    return true;
}

int main(void) {
    Object *a = object_new(1), *b = object_new(2);
    if (!a || !b) { release(a); release(b); return 1; }
    if (!set_child(a, b) || !set_child(a, b)) {
        release(a); release(b); return 1;
    }
    printf("child count: %zu\n", b->refs);
    release(b); /* a still owns b */
    release(a); /* releases its child */
    return 0;
}

Successful output is child count: 2, destroy 1, then destroy 2. Each constructor gives its caller one owned reference. The first set_child retains b, making two; assigning the same child again retains before releasing the old edge, leaving two. Releasing the caller’s b leaves the edge owned by a. Releasing a destroys it and releases that edge, destroying b. A failed retain leaves the old slot unchanged. Null is allowed as an empty edge.

The API requires live objects and one release for each owned reference; it cannot safely detect a release through a dangling pointer or an extra release after destruction. The count is non-atomic and cascading release is recursive, so it is not a concurrent or bounded-stack implementation. An array setter applies the same ordering per slot; a vector retains each of its three edges, including duplicates. If retaining a later edge fails, release every earlier retain. Cyclic ownership needs explicit cycle breaking or another collection scheme; never call release on a merely borrowed reference.

Chapter index · Course index