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.
#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
calls 3, live 2, b failed
live after two frees: 1fail_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_atandlive, passed through theAllocatorcontext. - "Fail the next call":
probe.fail_at = probe.calls + 1just 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
- Build a list with a few values through the probe allocator.
- Snapshot its state, fail the next allocation, call the operation, and compare the snapshot.
- Repeat the operation with failure disabled and check the success result.
- Destroy the list and check
live == 0. - 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.
livestays 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_atwas 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 withNDEBUG, so the append itself disappeared. Call first, then assert the saved result.
Practice
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.
#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
#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;
}failed: nomem, total still -1, live 1
ok: total 100, live 1
order kept: 40 10 30 20
destroyed: live 0Each 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.
Check your prediction
coding: 1 sessions, 40 minutes
reading: 2 sessions, 35 minutes
Analyzer checks passedFind 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.
Completion is saved in this browser only. It does not measure mastery.