Skip to content

Creation and Destruction Contracts

The Course
•
40 min study

An opaque type cannot live on the caller's stack, so the library must create it and, later, destroy it. That pair of functions is where most C resource bugs are born. A caller that forgets to destroy leaks memory. A caller that destroys twice corrupts the allocator. A caller that keeps using a handle after destroying it reads memory that may already belong to something else. None of these mistakes is visible in the pointer type: Decoder * looks the same whether it owns live storage or points at freed memory.

C has no destructor and no borrow checker, so ownership has to be a written contract. For a heap handle, the contract has four clauses:

  • Create returns a pointer the caller now owns, or NULL if any resource could not be acquired. A NULL result means nothing was acquired and nothing needs releasing.
  • Destroy ends the object's lifetime and releases everything create acquired. After destroy, every copy of that pointer is dangling.
  • Destroy accepts NULL and does nothing, just as free(NULL) does. This keeps cleanup paths simple.
  • Destroying the same non-NULL handle twice is invalid. The library cannot detect it, so the contract forbids it.

Predict and run

Read the program before pressing Run. Write down its output and say which statement produces it.

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

typedef struct { int value; } Handle;
Handle *create(void) {
    Handle *handle = malloc(sizeof *handle);
    if (handle != NULL) { handle->value = 7; }
    return handle;
}
void destroy(Handle *handle) { free(handle); }

int main(void) {
    Handle *handle = create();
    if (handle == NULL) { return 1; }
    printf("%d\n", handle->value);
    destroy(handle);
    return 0;
}
Check your prediction
Text
7

create initializes the object only after checking that malloc succeeded, because writing through NULL is undefined behavior. main checks the result before the first use. Ownership passes from create to main on return, and back to the library at destroy. After that line, handle still holds the old address, but using it in any way, even printing handle->value, is undefined.

Aliases are not copies

Assigning a handle copies the address, not the object:

C
Decoder *first = decoder_create(telemetry_default_allocator());
Decoder *second = first;      /* two names, one owner */
decoder_destroy(first);
decoder_destroy(second);      /* double free: undefined behavior */

Built with -fsanitize=address, a program like this stops at the second destroy with a report such as:

Shell
==12345==ERROR: AddressSanitizer: attempting double-free on 0x602000000010 in thread T0

Without a sanitizer, the same program might run silently and corrupt the allocator's bookkeeping, with a crash appearing much later in unrelated code. That delay is why you should run your tests under AddressSanitizer whenever your native toolchain supports it. If the caller needs two independent decoders, it calls create twice.

The allocator context must outlive the handle

The project's decoder_create takes a TelemetryAllocator: two callbacks and a void *context. The decoder copies the struct, so the callbacks and context pointer are stored inside the handle. The pointed-to context is only borrowed, though. If the caller's context lives on the stack of a function that returns before decoder_destroy runs, destroy will call the deallocator with a dangling context. The header states this as "allocator callbacks/context must remain valid until destroy". Day 5 builds a test allocator that relies on it.

Construction that can fail halfway

You already know the rule from C Intermediate's cleanup lesson: when create acquires a second resource and that fails, it releases the first before returning NULL, because a caller that receives NULL correctly releases nothing. Destroy releases in reverse order of acquisition, so a buffer owned by the struct goes before the struct.

What is new at this level is proving it for every acquisition, not only the one that is easy to break. A switch that fails "the next allocation" only ever reaches the first one, so the cleanup after the second is never run. A counter reaches each in turn:

C
static int calls = 0;
static int fail_at = 0;   /* 0: never fail; N: the Nth allocation fails */
static void *tracked_alloc(size_t size) {
    ++calls;
    if (calls == fail_at) { return NULL; }
    void *block = malloc(size);
    if (block != NULL) { ++live; }
    return block;
}

Setting fail_at = calls + 1 fails the first allocation of the next create; calls + 2 fails the second. Together with a live count of outstanding blocks, that turns "did create clean up?" into a number you can print.

Practice

Exercise

Your turn

Write Label *label_create(const char *text), which allocates a Label and an owned copy of text, and void label_destroy(Label *label), which accepts NULL. Use the starter's tracked_alloc and tracked_free for every allocation. The starter's try_create fails one chosen allocation of a create, prints the live count and destroys whatever came back. main must print:

Shell
Label: bay-4, live 2
Struct fails: NULL, live 2
Text fails: NULL, live 2
After destroy: live 0
Your workspace C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int live = 0;
static int calls = 0;
static int fail_at = 0;   /* 0: never fail; N: the Nth allocation fails */
static void *tracked_alloc(size_t size) {
    ++calls;
    if (calls == fail_at) { return NULL; }
    void *block = malloc(size);
    if (block != NULL) { ++live; }
    return block;
}
static void tracked_free(void *block) {
    if (block != NULL) { --live; free(block); }
}

typedef struct { char *text; } Label;

/* Write label_create and label_destroy here. */

static void try_create(const char *what, int step) {
    fail_at = calls + step;   /* fail this create's first or second allocation */
    Label *label = label_create("bay-5");
    printf("%s fails: %s, live %d\n", what, label == NULL ? "NULL" : "handle", live);
    label_destroy(label);
    fail_at = 0;
}

int main(void) {
    Label *first = label_create("bay-4");
    if (first == NULL) { return 1; }
    printf("Label: %s, live %d\n", first->text, live);
    try_create("Struct", 1);
    try_create("Text", 2);
    label_destroy(first);
    printf("After destroy: live %d\n", live);
    return 0;
}
Hint 1: the idea

There are two places create can fail, and the "Text" line reaches the second one. At that moment the struct is already allocated and counted in live, and the caller will receive NULL, so only create itself can still release it.

Hint 2: a first step

Write create with both allocations and a NULL check after each, but have the second check just return NULL;. Run it: the "Text" line says live 3 and the last line live 1, which is the leaked struct. Now make that path undo the first acquisition and run again.

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

static int live = 0;
static int calls = 0;
static int fail_at = 0;   /* 0: never fail; N: the Nth allocation fails */
static void *tracked_alloc(size_t size) {
    ++calls;
    if (calls == fail_at) { return NULL; }
    void *block = malloc(size);
    if (block != NULL) { ++live; }
    return block;
}
static void tracked_free(void *block) {
    if (block != NULL) { --live; free(block); }
}

typedef struct { char *text; } Label;

Label *label_create(const char *text) {
    Label *label = tracked_alloc(sizeof *label);
    if (label == NULL) { return NULL; }
    size_t size = strlen(text) + 1;
    label->text = tracked_alloc(size);
    if (label->text == NULL) { tracked_free(label); return NULL; }
    memcpy(label->text, text, size);
    return label;
}
void label_destroy(Label *label) {
    if (label == NULL) { return; }
    tracked_free(label->text);
    tracked_free(label);
}

static void try_create(const char *what, int step) {
    fail_at = calls + step;   /* fail this create's first or second allocation */
    Label *label = label_create("bay-5");
    printf("%s fails: %s, live %d\n", what, label == NULL ? "NULL" : "handle", live);
    label_destroy(label);
    fail_at = 0;
}

int main(void) {
    Label *first = label_create("bay-4");
    if (first == NULL) { return 1; }
    printf("Label: %s, live %d\n", first->text, live);
    try_create("Struct", 1);
    try_create("Text", 2);
    label_destroy(first);
    printf("After destroy: live %d\n", live);
    return 0;
}
Text
Label: bay-4, live 2
Struct fails: NULL, live 2
Text fails: NULL, live 2
After destroy: live 0

The live count is the evidence: the "Text" line stays at 2 only because the struct was released inside create, and the last line reaches zero only if every successful acquisition was released exactly once. label_destroy(label) in try_create receives NULL both times, which is safe because destroy accepts it. The next lesson looks at the other side of ownership: memory the library only borrows during a call.

Was this article helpful?

Your response is saved on this device.