Skip to content

Checkpoint: Prove Failure Guarantees

The Course
•
40 min study

Every contract in this course has a failure clause: "failure leaves contents, length and capacity unchanged", "allocation failure prints nothing", "destroy releases all storage". A program that only ever succeeds says nothing about those clauses. This checkpoint turns them into checks you can run: you force the failure with a probe allocator, then inspect the state the contract promised to keep. Finally you ask a harder question: would your tests notice if the code were wrong? A mutation is a small, deliberate bug. If the tests still pass after it, they are not testing what you think.

Predict and run

Read the program before pressing Run. Write down both lines of its output and explain what a non-zero count at the end would mean.

Predict before running C
#include <stdio.h>
#include <stdlib.h>

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

static void *probe_alloc(Probe *probe, size_t size) {
    probe->calls++;
    if (probe->calls == probe->fail_at) { return NULL; }
    void *block = malloc(size);
    if (block != NULL) { probe->live++; }
    return block;
}

static void probe_free(Probe *probe, void *block) {
    if (block != NULL) { probe->live--; free(block); }
}

int main(void) {
    Probe probe = {0, 0, 0};
    void *a = probe_alloc(&probe, 8);
    probe.fail_at = probe.calls + 1;
    void *b = probe_alloc(&probe, 8);
    probe.fail_at = 0;
    void *c = probe_alloc(&probe, 8);
    printf("calls %zu, live %zu, b %s\n", probe.calls, probe.live,
           b == NULL ? "failed" : "ok");
    probe_free(&probe, a);
    probe_free(&probe, b);
    printf("live after two frees: %zu\n", probe.live);
    probe_free(&probe, c);
    return 0;
}
Check your prediction
Text
calls 3, live 2, b failed
live after two frees: 1

fail_at = calls + 1 makes the very next call fail, so b gets NULL and allocates nothing: three calls, two live blocks. Freeing b changes nothing, so after two frees one block is still live, c, which the last line releases. A count above 0 when a test ends means a leak; a release that drove it below zero would mean something was freed twice or freed through the wrong allocator. The project's probe_release asserts probe->live > 0 for that reason. assert stops the program when its condition is false, unless NDEBUG is defined, which removes every assertion.

What you will use

  • A probe allocator with calls, fail_at and live, passed through the Allocator context.
  • "Fail the next call": probe.fail_at = probe.calls + 1 just before the operation under test, and 0 afterward.
  • State snapshots: save the pointer, length, capacity and a total before the failing call, and compare after.
  • A live-block count of 0 after destroy, the leak check that needs no addresses.

Plan before you type

  1. Build a list with a few values through the probe allocator.
  2. Snapshot its state, fail the next allocation, call the operation, and compare the snapshot.
  3. Repeat the operation with failure disabled and check the success result.
  4. Destroy the list and check live == 0.
  5. Apply one mutation at a time and confirm that some check fails.
Prove it can fail

Once the expected lines appear, mutate the solution. Add *out = 0; as the first line of sorted_total, before the allocation, as if "resetting the result" were harmless: the failed call now changes the reported total, and the first line says total still 0 instead of total still -1. Next, delete the release of the temporary copy: the success line shows live 2 instead of live 1. Then make the sum loop stop one element early: the totals drop by 40. Each mutation must turn at least one line wrong. Restore the code after each.

Mistakes worth checking for

  • The failed call still reports a result. The output parameter was written before the allocation succeeded. Commit at the end.
  • live stays above 0 after destroy. A temporary block was never released, or destroy skipped the release when the length was 0.
  • The test passes, then a later test fails mysteriously. fail_at was not reset to 0, so an unrelated allocation failed.
  • The stored order changed after a report. The code sorted the list's own array instead of a copy.
  • Checks vanish in a release build. The test used assert(list_append(...) == STATUS_OK) and was built with NDEBUG, so the append itself disappeared. Call first, then assert the saved result.

Practice

Exercise

Your turn

Write Status sorted_total(const List *list, long *out). It allocates a temporary copy of the values through list->allocator, sorts the copy with qsort, adds the values, releases the copy and stores the sum. If the allocation fails it returns STATUS_NOMEM with *out unchanged. The list itself must never be reordered. The starter must print failed: nomem, total still -1, live 1, ok: total 100, live 1, order kept: 40 10 30 20, destroyed: live 0.

Your workspace C
#include <stdio.h>
#include <stdlib.h>
#include <string.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;
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 int compare_ints(const void *left, const void *right) {
    const int *a = left; const int *b = right;
    return (*a > *b) - (*a < *b);
}

/* Write sorted_total here. */

int main(void) {
    Probe probe = {0, 0, 0};
    List list = {NULL, 0, 0, {probe_resize, probe_release, &probe}};
    list.data = probe_resize(&probe, NULL, 4 * sizeof *list.data);
    if (list.data == NULL) { return 1; }
    list.capacity = 4;
    int values[4] = {40, 10, 30, 20};
    for (size_t i = 0; i < 4; ++i) { list.data[list.length++] = values[i]; }
    // Fail the next allocation and call sorted_total, then call it again normally.
    probe_release(&probe, list.data);
    printf("destroyed: live %zu\n", probe.live);
    return 0;
}
Hint 1: the idea

This is the project's report in miniature: a temporary allocation that can fail, work on the copy, and a release on the success path. The list is const, but only shallowly: const List * makes the struct's members read-only, not the ints that data points to, so qsort(list->data, ...) would still compile and reorder the caller's list. Sorting a copy is a rule you keep, not one the compiler enforces.

Hint 2: a first step

Write the success path first, ignoring failure: allocate the copy through the allocator, copy the values, sort, sum, release. In main, make only the normal call for now and print its line and the order; the ok and order kept lines should be right. Then decide what the failed allocation must return and what it must not touch.

Show one solution
Run the solution C
#include <stdio.h>
#include <stdlib.h>
#include <string.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;
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 int compare_ints(const void *left, const void *right) {
    const int *a = left; const int *b = right;
    return (*a > *b) - (*a < *b);
}

/* Requires a non-empty list. Failure leaves *out unchanged. */
Status sorted_total(const List *list, long *out) {
    int *copy = list->allocator.resize(list->allocator.context, NULL,
        list->length * sizeof *copy);
    if (copy == NULL) { return STATUS_NOMEM; }
    memcpy(copy, list->data, list->length * sizeof *copy);
    qsort(copy, list->length, sizeof *copy, compare_ints);
    long total = 0;
    for (size_t i = 0; i < list->length; ++i) { total += copy[i]; }
    list->allocator.release(list->allocator.context, copy);
    *out = total;
    return STATUS_OK;
}

int main(void) {
    Probe probe = {0, 0, 0};
    List list = {NULL, 0, 0, {probe_resize, probe_release, &probe}};
    list.data = probe_resize(&probe, NULL, 4 * sizeof *list.data);
    if (list.data == NULL) { return 1; }
    list.capacity = 4;
    int values[4] = {40, 10, 30, 20};
    for (size_t i = 0; i < 4; ++i) { list.data[list.length++] = values[i]; }
    long total = -1;
    probe.fail_at = probe.calls + 1;
    Status s = sorted_total(&list, &total);
    probe.fail_at = 0;
    printf("failed: %s, total still %ld, live %zu\n", s == STATUS_NOMEM ? "nomem" : "ok", total, probe.live);
    if (sorted_total(&list, &total) != STATUS_OK) { probe_release(&probe, list.data); return 1; }
    printf("ok: total %ld, live %zu\n", total, probe.live);
    printf("order kept: %d %d %d %d\n", list.data[0], list.data[1], list.data[2], list.data[3]);
    probe_release(&probe, list.data);
    printf("destroyed: live %zu\n", probe.live);
    return 0;
}
Text
failed: nomem, total still -1, live 1
ok: total 100, live 1
order kept: 40 10 30 20
destroyed: live 0

Each line checks one clause of the contract: failure commits nothing, success releases its temporary, the stored order is untouched, and everything is freed at the end. live 1 on both of the first two lines is the evidence that the copy did not leak. The copy is released before *out is written, but both happen only after the one step that can fail, so the order between them does not matter. The Requires comment matters too: with an empty list, the request would be 0 bytes, which this course never makes, and the project's report handles that case first by printing No records.

Challenge the real failure paths

The project's tests do the same with the real analyzer. They reject the first allocation, reject growth after four records, and check the pointer, length, capacity and total afterward. They fail the report's temporary copy and check that the collection is unchanged. They end with probe.live == 0. Run them.

Controlled allocation failures C
#include "analyzer.h" #include <assert.h> #include <stdlib.h> #include <string.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; assert(storage != NULL && probe->live > 0); --probe->live; free(storage); } int main(void) { /* Calls that change state run in their own statement and assert checks the saved status, so building with NDEBUG removes only the checks, not the work. */ AnalyzerStatus status; Record out = {"keep", 77}; const char *bad[] = {"", "reading", "reading 0", "reading 181", "Read 25", "reading -1", "reading +25", "reading 25x", "reading 25 extra", "reading 99999999999999999999999999999", "abcdefghijklmnopqrstuvwx 25"}; for (size_t i = 0; i < sizeof bad / sizeof bad[0]; ++i) { status = record_parse(bad[i], &out); assert(status == ANALYZER_INVALID); assert(strcmp(out.topic, "keep") == 0 && out.minutes == 77); } status = record_parse(NULL, &out); assert(status == ANALYZER_INVALID); status = record_parse("reading 25", NULL); assert(status == ANALYZER_INVALID); status = record_parse(" reading 001\r\n", &out); assert(status == ANALYZER_OK && out.minutes == 1); status = record_parse("abcdefghijklmnopqrstuvw 180", &out); assert(status == ANALYZER_OK && out.minutes == 180); Probe probe = {0, 1, 0}; Allocator allocator = {probe_resize, probe_release, &probe}; Analyzer analyzer; analyzer_init(&analyzer, allocator); Record reading = {"reading", 25}; Record coding = {"coding", 40}; assert(analyzer_total(&analyzer) == 0); status = analyzer_append(&analyzer, &reading); assert(status == ANALYZER_NOMEM); assert(analyzer.data == NULL && analyzer.length == 0 && analyzer.capacity == 0); probe.fail_at = 0; for (size_t i = 0; i < 4; ++i) { status = analyzer_append(&analyzer, &reading); assert(status == ANALYZER_OK); } Record *old = analyzer.data; size_t capacity = analyzer.capacity; probe.fail_at = probe.calls + 1; status = analyzer_append(&analyzer, &coding); assert(status == ANALYZER_NOMEM); assert(analyzer.data == old && analyzer.length == 4 && analyzer.capacity == capacity); assert(analyzer_total(&analyzer) == 100 && probe.live == 1); probe.fail_at = 0; /* Passing a borrowed element back into append is safe across growth. */ status = analyzer_append(&analyzer, &analyzer.data[0]); assert(status == ANALYZER_OK); assert(analyzer.length == 5 && analyzer_total(&analyzer) == 125); Record invalid = {"bad", 0}; status = analyzer_append(&analyzer, &invalid); assert(status == ANALYZER_INVALID && analyzer.length == 5); status = analyzer_remove(&analyzer, analyzer.length); assert(status == ANALYZER_INVALID); status = analyzer_remove(&analyzer, 0); assert(status == ANALYZER_OK && analyzer.length == 4); assert(analyzer_total(&analyzer) == 100); analyzer_destroy(&analyzer); analyzer_destroy(&analyzer); assert(probe.live == 0 && analyzer.data == NULL && analyzer.capacity == 0 && analyzer.length == 0); analyzer_init(&analyzer, allocator); status = analyzer_append(&analyzer, &reading); assert(status == ANALYZER_OK); status = analyzer_append(&analyzer, &coding); assert(status == ANALYZER_OK); Record short_reading = {"reading", 10}; status = analyzer_append(&analyzer, &short_reading); assert(status == ANALYZER_OK); probe.fail_at = probe.calls + 1; status = analyzer_report(&analyzer, stdout); assert(status == ANALYZER_NOMEM); assert(analyzer_total(&analyzer) == 75 && probe.live == 1); probe.fail_at = 0; status = analyzer_report(&analyzer, stdout); assert(status == ANALYZER_OK); assert(strcmp(analyzer.data[0].topic, "reading") == 0 && analyzer.data[0].minutes == 25); assert(probe.live == 1); status = analyzer_remove(&analyzer, 0); assert(status == ANALYZER_OK); assert(strcmp(analyzer.data[0].topic, "coding") == 0 && analyzer_total(&analyzer) == 50); status = analyzer_remove(&analyzer, 1); assert(status == ANALYZER_OK); status = analyzer_remove(&analyzer, 0); assert(status == ANALYZER_OK && analyzer_total(&analyzer) == 0); for (size_t i = 0; i < ANALYZER_LIMIT; ++i) { status = analyzer_append(&analyzer, &coding); assert(status == ANALYZER_OK); } status = analyzer_append(&analyzer, &reading); assert(status == ANALYZER_FULL); assert(analyzer.length == ANALYZER_LIMIT && analyzer_total(&analyzer) == 40960); analyzer_destroy(&analyzer); assert(probe.live == 0); (void)status; /* these are only read by assert, which NDEBUG removes */ (void)old; (void)capacity; puts("Analyzer checks passed"); return 0; } #include "analyzer.h" #include <errno.h> #include <stdint.h> #include <stdlib.h> #include <string.h> static void *default_resize(void *context, void *old, size_t bytes) { (void)context; return realloc(old, bytes); } static void default_release(void *context, void *storage) { (void)context; free(storage); } Allocator analyzer_default_allocator(void) { Allocator allocator = {default_resize, default_release, NULL}; return allocator; } void analyzer_init(Analyzer *analyzer, Allocator allocator) { analyzer->data = NULL; analyzer->length = 0; analyzer->capacity = 0; analyzer->allocator = allocator; } void analyzer_destroy(Analyzer *analyzer) { if (analyzer->data != NULL) { analyzer->allocator.release(analyzer->allocator.context, analyzer->data); } analyzer->data = NULL; analyzer->length = 0; analyzer->capacity = 0; } static int whitespace(char ch) { return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; } static int valid_record(const Record *record) { if (record == NULL || record->minutes < 1 || record->minutes > 180) { return 0; } size_t i = 0; while (i < TOPIC_CAPACITY && record->topic[i] >= 'a' && record->topic[i] <= 'z') { ++i; } return i > 0 && i < TOPIC_CAPACITY && record->topic[i] == '\0'; } AnalyzerStatus record_parse(const char *line, Record *out) { if (line == NULL || out == NULL) { return ANALYZER_INVALID; } while (whitespace(*line)) { ++line; } Record candidate = {{0}, 0}; size_t length = 0; while (*line >= 'a' && *line <= 'z') { if (length >= TOPIC_CAPACITY - 1) { return ANALYZER_INVALID; } candidate.topic[length++] = *line++; } if (length == 0 || !whitespace(*line)) { return ANALYZER_INVALID; } while (whitespace(*line)) { ++line; } /* Require a decimal digit first: signed notation is outside this format. */ if (*line < '0' || *line > '9') { return ANALYZER_INVALID; } errno = 0; char *end = NULL; long minutes = strtol(line, &end, 10); if (errno == ERANGE || end == line || minutes < 1 || minutes > 180) { return ANALYZER_INVALID; } while (whitespace(*end)) { ++end; } if (*end != '\0') { return ANALYZER_INVALID; } candidate.minutes = (int)minutes; *out = candidate; return ANALYZER_OK; } AnalyzerStatus analyzer_append(Analyzer *analyzer, const Record *record) { if (!valid_record(record)) { return ANALYZER_INVALID; } if (analyzer->length >= ANALYZER_LIMIT) { return ANALYZER_FULL; } /* A caller may pass &data[i]. Copy it before realloc can invalidate it. */ Record candidate = *record; if (analyzer->length == analyzer->capacity) { size_t capacity = analyzer->capacity == 0 ? 4 : analyzer->capacity * 2; if (capacity > ANALYZER_LIMIT) { capacity = ANALYZER_LIMIT; } if (capacity > SIZE_MAX / sizeof *analyzer->data) { return ANALYZER_NOMEM; } void *grown = analyzer->allocator.resize(analyzer->allocator.context, analyzer->data, capacity * sizeof *analyzer->data); if (grown == NULL) { return ANALYZER_NOMEM; } analyzer->data = grown; analyzer->capacity = capacity; } analyzer->data[analyzer->length] = candidate; ++analyzer->length; return ANALYZER_OK; } AnalyzerStatus analyzer_remove(Analyzer *analyzer, size_t index) { if (index >= analyzer->length) { return ANALYZER_INVALID; } size_t following = analyzer->length - index - 1; if (following > 0) { memmove(&analyzer->data[index], &analyzer->data[index + 1], following * sizeof *analyzer->data); } --analyzer->length; return ANALYZER_OK; } long analyzer_total(const Analyzer *analyzer) { long total = 0; for (size_t i = 0; i < analyzer->length; ++i) { total += analyzer->data[i].minutes; } return total; } static int compare_records(const void *left, const void *right) { const Record *a = left; const Record *b = right; int topic = strcmp(a->topic, b->topic); if (topic != 0) { return topic; } return (a->minutes > b->minutes) - (a->minutes < b->minutes); } AnalyzerStatus analyzer_report(const Analyzer *analyzer, FILE *output) { if (analyzer->length == 0) { fprintf(output, "No records\n"); return ANALYZER_OK; } Record *sorted = analyzer->allocator.resize(analyzer->allocator.context, NULL, analyzer->length * sizeof *sorted); if (sorted == NULL) { return ANALYZER_NOMEM; } memcpy(sorted, analyzer->data, analyzer->length * sizeof *sorted); qsort(sorted, analyzer->length, sizeof *sorted, compare_records); size_t i = 0; while (i < analyzer->length) { size_t start = i; long minutes = 0; while (i < analyzer->length && strcmp(sorted[start].topic, sorted[i].topic) == 0) { minutes += sorted[i].minutes; ++i; } fprintf(output, "%s: %zu sessions, %ld minutes\n", sorted[start].topic, i - start, minutes); } analyzer->allocator.release(analyzer->allocator.context, sorted); return ANALYZER_OK; } #ifndef ANALYZER_H #define ANALYZER_H #include <stddef.h> #include <stdio.h> #define TOPIC_CAPACITY 24 #define ANALYZER_LIMIT 1024 typedef enum { ANALYZER_OK, ANALYZER_INVALID, ANALYZER_FULL, ANALYZER_NOMEM } AnalyzerStatus; typedef struct { char topic[TOPIC_CAPACITY]; int minutes; } Record; /* resize has realloc semantics: failure preserves old storage. release frees it. Both callbacks use the same allocator/context, which must outlive the analyzer. */ 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; /* Owns data. Do not shallow-copy this struct or free data yourself. Invariant: length <= capacity <= ANALYZER_LIMIT; only [0,length) is initialized. Borrowed element pointers expire after successful growth, removal or destroy. */ typedef struct { Record *data; size_t length; size_t capacity; Allocator allocator; } Analyzer; Allocator analyzer_default_allocator(void); /* Initialize once, using a valid allocator. Destroy before reinitializing. */ void analyzer_init(Analyzer *analyzer, Allocator allocator); void analyzer_destroy(Analyzer *analyzer); /* Lowercase ASCII topic (1..23 letters), whitespace, decimal duration 1..180. Leading/trailing whitespace is allowed. No extra fields. Failure preserves out. */ AnalyzerStatus record_parse(const char *line, Record *out); /* Failure leaves contents, length and capacity unchanged. Copies record by value. */ AnalyzerStatus analyzer_append(Analyzer *analyzer, const Record *record); AnalyzerStatus analyzer_remove(Analyzer *analyzer, size_t index); /* Empty total is zero. Caller supplies an initialized analyzer. */ long analyzer_total(const Analyzer *analyzer); /* Sort a temporary copy by topic/minutes. Does not reorder stored records. Allocation failure prints nothing. Caller checks ferror(output) for I/O errors. */ AnalyzerStatus analyzer_report(const Analyzer *analyzer, FILE *output); #endif
Check your prediction
Text
coding: 1 sessions, 40 minutes
reading: 2 sessions, 35 minutes
Analyzer checks passed

Find probe_resize and probe_release in test_analyzer.c. Identify the line that makes growth fail, the assertion that proves the old storage is still owned afterward, and the one that proves every block was released. Then apply a mutation in analyzer.c: change the loop in analyzer_total to stop one record early. An assertion fails and the program stops with a message naming the line. Restore the loop. A live-block count is good evidence, not a complete memory checker: the optional sanitizer build on Day 7 also catches invalid reads and writes.

Was this article helpful?

Your response is saved on this device.