Tracing and sweeping a graph

Lesson 14 of 14 · C memory foundations

A tracing collector asks which managed objects are reachable from roots, rather than how many references each has. A root is an entry point known to the runtime, such as a reference held in a registered virtual-machine frame or a global. The runtime also tracks all managed allocations so that it can later enumerate candidates for sweeping. Tracking an object does not itself make it reachable.

registered frame -> A -> B
                         ^  |
                         |__|     C <-> D   (no root)

First mark roots, then follow every managed edge from marked containers. Here A and B survive; C and D are unreachable even though they form a cycle. A gray worklist holds marked objects whose children still need inspection. Mark each object as part of enqueueing and skip already-marked objects, so cycles terminate. With a fallible worklist, a failed enqueue must abort the trace rather than leave an object marked but unqueued. Scalar and string objects have no managed children; a vector visits its three object references; an array visits its initialized elements. A frame disappearing removes its registered roots, but other roots may still reach those objects.

After tracing completes, scan the tracked object list. Unmarked objects are removed and destroyed; marked survivors have their marks cleared for the next collection. Destruction frees an object’s private buffers but does not recursively free managed children: the sweep decides each child’s fate independently. Finally release frame and tracking structures at runtime shutdown.

This simple stop-the-world model assumes the mutator does not change the graph during collection and that every live root and edge is visible. If allocating or growing the gray worklist fails, abort collection safely and do not sweep partially traced objects; restore mark state before another attempt. Root registration during construction must protect objects across any possible collection. Real concurrent or incremental collectors require barriers and synchronization. Tracing handles unreachable cycles, but can introduce pauses and metadata costs; neither scheme is automatically faster for every workload.

Complete fixed-point collector

This standalone alternative avoids an allocating gray worklist: it repeatedly scans the tracked list until no marked object has an unmarked child. That trades speed for a simpler failure story. Each object has one managed edge; extending it to arrays or vectors means visiting every initialized child. A frame here has one root, and the linked frame chain represents nested registrations.

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

typedef struct Object Object;
struct Object { int id; bool marked; Object *edge, *next; };
typedef struct Frame Frame;
struct Frame { Object *root; Frame *previous; };
typedef struct { Object *objects; Frame *frames; } VM;

/* Collection runs only when explicitly requested, never in new_object. */
static Object *new_object(VM *vm, int id) {
    Object *o = malloc(sizeof *o);
    if (!o) return NULL;
    *o = (Object){.id = id, .marked = false, .edge = NULL,
                  .next = vm->objects};
    vm->objects = o;
    return o;
}

static void collect(VM *vm) {
    /* This allocation-free fixed-point trace handles cycles without recursion. */
    for (Frame *f = vm->frames; f; f = f->previous)
        if (f->root) f->root->marked = true;
    bool changed;
    do {
        changed = false;
        for (Object *o = vm->objects; o; o = o->next) {
            if (o->marked && o->edge && !o->edge->marked) {
                o->edge->marked = true;
                changed = true;
            }
        }
    } while (changed);

    Object **link = &vm->objects;
    while (*link) {
        Object *o = *link;
        if (o->marked) {
            o->marked = false;
            link = &o->next;
        } else {
            *link = o->next;
            printf("collect %d\n", o->id);
            free(o); /* edge is managed independently */
        }
    }
}

int main(void) {
    VM vm = {0};
    Object *a = new_object(&vm, 1), *b = new_object(&vm, 2);
    Object *c = new_object(&vm, 3), *d = new_object(&vm, 4);
    if (!a || !b || !c || !d) { collect(&vm); return 1; }
    a->edge = b;
    c->edge = d; d->edge = c;
    Frame frame = {.root = a, .previous = NULL};
    vm.frames = &frame;
    puts("first collection");
    collect(&vm);
    vm.frames = frame.previous; /* no roots remain */
    puts("second collection");
    collect(&vm);
    return 0;
}

The first collection prints collect 4 then collect 3: their cycle has no root. Objects 1 and 2 survive because the frame roots 1 and its edge reaches 2. Removing the frame before the second collection prints collect 2 then collect 1. Order follows this example’s linked-list insertion, not a general collector guarantee. All construction is complete before the explicit collection; on allocation failure, no roots exist and a collection safely frees whatever was allocated.

Each pass propagates reachability at least one edge farther where necessary; marking before further scanning makes cycles harmless. At the fixed point, no reachable edge leads to an unmarked object. The pointer-to-pointer sweep unlinks an unreachable node before freeing it, and clears survivor marks for the next collection. Private buffers would be freed with their wrapper; managed child objects are not recursively freed. The list tracks candidates, not roots. Fixed-point scanning can take quadratic time on a long chain and is illustrative, not a production performance design.

The contract is essential: every frame root and every edge must be null or point to a live object tracked by this same VM; the mutator is stopped during collection. A C local pointer alone is not a root. After sweep, never access a collected object or a stale local alias. If collection could run during construction, register every live intermediate before the collection point. A worklist version must abort without sweeping if a push fails, clear all partial marks, and retry only after restoring a consistent state.

Gray-worklist walkthrough

The separate standalone worklist.c implements a gray stack rather than repeated scanning. It has three nullable managed edges per object and any number of roots in a frame, so the edge loop models visiting vector components or array slots; it is not wired to the reference-counted variants. Its objects are owned by the VM’s tracking list, not by edges. Collection is explicit and stop-the-world. Compile and run from this lesson’s directory, without NDEBUG because the demonstration uses assertions with side effects:

cc -std=c11 -Wall -Wextra -Wpedantic -Werror worklist.c -o worklist
./worklist

Expected output:

failed trace: no sweep
first collection:
collect 4
collect 3
second collection:
collect 2
collect 1

Initially roots 1 and 2 reach each other; 3 and 4 form another cycle. In the injected failure, roots 1 and 2 have already been marked when growing the gray stack for a third root fails. The collector frees the worklist, clears all partial marks, returns failure and does not sweep. After removing that third root and disabling failure, retry marks the two reachable objects, drains the stack, then sweeps the unreachable cycle. Removing the frame lets the second successful collection sweep the remaining cycle. Print order comes from list insertion order, not a collector guarantee.

shade skips null or already-marked edges; otherwise it first pushes successfully, then immediately marks. With mutation stopped, every marked object is either queued gray or has already been popped and had its edges visited (black). Thus duplicates and cycles cannot enqueue indefinitely. If any push fails, the algorithm abandons that invariant’s partial state before any sweep. Only when the stack is empty may sweep treat unmarked tracked objects as unreachable; survivor marks are reset for the next pass. Each complete trace visits reachable vertices and their edges once, followed by a linear sweep of tracked objects; worklist storage can grow with reachable objects.

All nonnull roots and edges must point to live objects tracked by this VM, and the mutator must not alter them during collection. A C local is not a root; do not use aliases after their objects are collected. Allocation itself never triggers collection here. An automatic collector would need registration for every live intermediate, and incremental/concurrent collection would require barriers and synchronization. This toy has no strings, dynamic arrays or production VM integration; use the earlier fixed-point version to compare the allocation-free alternative.

Chapter index · Course index