typestar

One exit, everything freed in C

The acquire-check-goto pattern, written out in full.

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

int process(const char *path, size_t n) {
    int result = 0;
    int *buffer = NULL;
    char *scratch = NULL;

    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        goto done;
    }
    buffer = malloc(n * sizeof(int));
    if (buffer == NULL) {
        goto close_file;
    }
    scratch = malloc(n);
    if (scratch == NULL) {
        goto free_buffer;
    }

    result = (int) fread(scratch, 1, n, f);

    free(scratch);
free_buffer:
    free(buffer);
close_file:
    fclose(f);
done:
    return result;
}

How it works

  1. Each acquisition has a label to unwind to.
  2. Labels appear in reverse order of acquisition.
  3. Nothing is freed twice and nothing is missed.

Keywords and builtins used here

The run, in numbers

Lines
31
Characters to type
468
Tokens
144
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 2 of 2 in Errors & cleanup, step 9 of 11 in APIs, errors & testing.

← Previous Next →