Skip to content

Inject Allocation Failure

The Course
•
40 min study

Every append you have written has a branch for realloc returning NULL, and you have never seen that branch run. That is normal: on a desktop machine, small allocations essentially never fail. Requesting enormous blocks until memory runs out is a poor test. It is slow, it affects everything else on the machine, and on Linux it often does not even fail at the request, because the system may promise memory it later cannot supply. Untested code is where bugs live, and the branch that only runs when the system is already in trouble is the worst place for one.

The fix is dependency injection: the collection does not call realloc directly. It calls a function pointer that the caller supplies. Production code passes a thin wrapper around realloc and free; a test passes a probe that counts calls and fails exactly the one it chooses.

Predict and run

The probe below fails its second call. Read the program before pressing Run and write down both lines.

Predict before running C
#include <stdio.h>

typedef struct { size_t calls; size_t fail_at; } Probe;

int allowed(void *context) {
    Probe *probe = context;
    ++probe->calls;
    return probe->calls != probe->fail_at;
}

int main(void) {
    Probe probe = {0, 2};
    int first = allowed(&probe);
    int second = allowed(&probe);
    int third = allowed(&probe);
    printf("%d %d %d\n", first, second, third);
    printf("calls: %zu\n", probe.calls);
    return 0;
}
Check your prediction
Text
1 0 1
calls: 3

The count increases before the comparison, so the first call sees 1, the second sees 2 and fails, and the third succeeds again. Setting fail_at to 0 disables failure, because the count is at least 1 by the time it is compared. The three calls are separate statements on purpose: inside one printf(..., allowed(&probe), allowed(&probe)), the order in which C evaluates function arguments is unspecified, so the results could be swapped.

The project's allocator interface

analyzer.h declares two callback types and bundles them with a context pointer:

C
typedef void *(*ResizeFn)(void *context, void *old, size_t bytes);
typedef void (*ReleaseFn)(void *context, void *storage);
typedef struct { ResizeFn resize; ReleaseFn release; void *context; } Allocator;

resize has the same contract as realloc: with old equal to NULL it allocates, and on failure it returns NULL and leaves the old block untouched. release frees a block that resize returned. analyzer_default_allocator wraps the real realloc and free and ignores the context.

Three rules come with the interface, and the header states them:

  • A block must be released through the same allocator that created it. Passing a probe-allocated block to some other free would corrupt the probe's counts.
  • The context must outlive every analyzer that uses it. If the probe were a local variable in a function that returned, the analyzer would hold a dangling pointer.
  • A fake resize that fails must not free the old block. Otherwise the collection's "unchanged on failure" promise would be broken by the test itself.

A probe that also counts live blocks

Failure is only half of what a test needs. It also needs evidence that nothing leaked, without printing addresses that differ on every run. The probe counts live blocks: one more when a fresh block is created, one fewer when a block is released. A resize of an existing block does not change the count.

Fail the first allocation C
#include <stdio.h>
#include <stdlib.h>

typedef struct { size_t calls; size_t fail_at; size_t live; } Probe;

static void *probe_resize(void *context, void *old, size_t bytes) {
    Probe *probe = context;
    ++probe->calls;
    if (probe->calls == probe->fail_at) { return NULL; }
    int new_block = old == NULL;
    void *result = realloc(old, bytes);
    if (result != NULL && new_block) { ++probe->live; }
    return result;
}

static void probe_release(void *context, void *storage) {
    Probe *probe = context;
    if (storage != NULL) { --probe->live; free(storage); }
}

int main(void) {
    Probe probe = {0, 1, 0};
    int *data = probe_resize(&probe, NULL, 4 * sizeof *data);
    printf("first request: %s, live %zu\n", data == NULL ? "failed" : "ok", probe.live);
    data = probe_resize(&probe, NULL, 4 * sizeof *data);
    printf("second request: %s, live %zu\n", data == NULL ? "failed" : "ok", probe.live);
    probe_release(&probe, data);
    printf("after release: live %zu, calls %zu\n", probe.live, probe.calls);
    return 0;
}
Text
first request: failed, live 0
second request: ok, live 1
after release: live 0, calls 2

The probe records whether old was NULL in new_block before calling realloc, because after a successful realloc the old pointer must not be used, not even in a comparison. The project's test_analyzer.c does the same.

Choosing the failure point

Tests pick a call number relative to what has happened so far. To fail the growth that a fifth append triggers, set probe.fail_at = probe.calls + 1 right before that append: "fail the next allocation". Afterward, set fail_at back to 0. This keeps tests independent of how many allocations earlier steps made.

Practice

Exercise

Your turn

The starter contains a small List that allocates through an Allocator. Write probe_resize and probe_release as above, then make main check three things: the first append fails with NOMEM and leaves the list empty; four appends then succeed; failing the next allocation makes the fifth append return NOMEM with length, capacity and contents unchanged. Expected output: first append: nomem, length 0, capacity 0, live 0, four appends: length 4, capacity 4, live 1, fifth append: nomem, length 4, capacity 4, last 40, destroyed: live 0.

Your workspace C
#include <stdio.h>
#include <stdlib.h>

typedef enum { STATUS_OK, STATUS_NOMEM } Status;
typedef void *(*ResizeFn)(void *context, void *old, size_t bytes);
typedef void (*ReleaseFn)(void *context, void *storage);
typedef struct { ResizeFn resize; ReleaseFn release; void *context; } Allocator;
typedef struct { int *data; size_t length; size_t capacity; Allocator allocator; } List;

Status list_append(List *list, int value) {
    if (list->length == list->capacity) {
        size_t capacity = list->capacity == 0 ? 4 : list->capacity * 2;
        int *grown = list->allocator.resize(list->allocator.context, list->data,
            capacity * sizeof *grown);
        if (grown == NULL) { return STATUS_NOMEM; }
        list->data = grown;
        list->capacity = capacity;
    }
    list->data[list->length++] = value;
    return STATUS_OK;
}

void list_destroy(List *list) {
    if (list->data != NULL) { list->allocator.release(list->allocator.context, list->data); }
    list->data = NULL;
    list->length = 0;
    list->capacity = 0;
}

typedef struct { size_t calls; size_t fail_at; size_t live; } Probe;
/* Write probe_resize and probe_release here. */

int main(void) {
    Probe probe = {0, 1, 0};
    List list = {NULL, 0, 0, {probe_resize, probe_release, &probe}};
    // Check the first-allocation failure, four appends, and a failed growth.
    list_destroy(&list);
    printf("destroyed: live %zu\n", probe.live);
    return 0;
}
Hint 1: the idea

The probe is created before the list and lives in main until after list_destroy, so the list's context pointer is valid for the whole test. You control failures only through probe.fail_at.

Hint 2: a first step

Write the two probe functions and only the first check in main, and run: the first line must say nomem with live 0. Then decide, for the fifth append, how to set probe.fail_at from probe.calls so that exactly the next allocation fails, whatever number it turns out to be.

Show one solution
Run the solution C
#include <stdio.h>
#include <stdlib.h>

typedef enum { STATUS_OK, STATUS_NOMEM } Status;
typedef void *(*ResizeFn)(void *context, void *old, size_t bytes);
typedef void (*ReleaseFn)(void *context, void *storage);
typedef struct { ResizeFn resize; ReleaseFn release; void *context; } Allocator;
typedef struct { int *data; size_t length; size_t capacity; Allocator allocator; } List;

Status list_append(List *list, int value) {
    if (list->length == list->capacity) {
        size_t capacity = list->capacity == 0 ? 4 : list->capacity * 2;
        int *grown = list->allocator.resize(list->allocator.context, list->data,
            capacity * sizeof *grown);
        if (grown == NULL) { return STATUS_NOMEM; }
        list->data = grown;
        list->capacity = capacity;
    }
    list->data[list->length++] = value;
    return STATUS_OK;
}

void list_destroy(List *list) {
    if (list->data != NULL) { list->allocator.release(list->allocator.context, list->data); }
    list->data = NULL;
    list->length = 0;
    list->capacity = 0;
}

typedef struct { size_t calls; size_t fail_at; size_t live; } Probe;

static void *probe_resize(void *context, void *old, size_t bytes) {
    Probe *probe = context;
    ++probe->calls;
    if (probe->calls == probe->fail_at) { return NULL; }
    int new_block = old == NULL;
    void *result = realloc(old, bytes);
    if (result != NULL && new_block) { ++probe->live; }
    return result;
}

static void probe_release(void *context, void *storage) {
    Probe *probe = context;
    if (storage != NULL) { --probe->live; free(storage); }
}

static const char *name(Status status) { return status == STATUS_OK ? "ok" : "nomem"; }

int main(void) {
    Probe probe = {0, 1, 0};
    List list = {NULL, 0, 0, {probe_resize, probe_release, &probe}};
    Status s = list_append(&list, 10);
    printf("first append: %s, length %zu, capacity %zu, live %zu\n",
        name(s), list.length, list.capacity, probe.live);
    probe.fail_at = 0;
    for (int value = 10; value <= 40; value += 10) {
        if (list_append(&list, value) != STATUS_OK) { list_destroy(&list); return 1; }
    }
    printf("four appends: length %zu, capacity %zu, live %zu\n",
        list.length, list.capacity, probe.live);
    probe.fail_at = probe.calls + 1;
    s = list_append(&list, 50);
    probe.fail_at = 0;
    printf("fifth append: %s, length %zu, capacity %zu, last %d\n",
        name(s), list.length, list.capacity, list.data[list.length - 1]);
    list_destroy(&list);
    printf("destroyed: live %zu\n", probe.live);
    return 0;
}
Text
first append: nomem, length 0, capacity 0, live 0
four appends: length 4, capacity 4, live 1
fifth append: nomem, length 4, capacity 4, last 40
destroyed: live 0

Both failure branches have now run on every execution, deterministically. The third line proves the "unchanged on failure" promise: the old block is still owned, still holds 40 at the end, and live stays 1. The last line proves list_destroy released it. The checkpoint next runs the same kind of test against the real analyzer, including its report copy, and introduces mutations to check that the tests are strong enough.

Was this article helpful?

Your response is saved on this device.