typestar

goto for cleanup in C

The one goto pattern C programmers defend: a single exit that frees what was taken.

#include <stdlib.h>

int build(int n, int **out) {
    int *first = malloc((size_t) n * sizeof(int));
    if (first == NULL) {
        goto fail_first;
    }
    int *second = malloc((size_t) n * sizeof(int));
    if (second == NULL) {
        goto fail_second;
    }
    for (int i = 0; i < n; i++) {
        first[i] = i;
        second[i] = i * i;
    }
    free(second);
    *out = first;
    return 1;

fail_second:
    free(first);
fail_first:
    *out = NULL;
    return 0;
}

How it works

  1. Every failure jumps to one label instead of repeating frees.
  2. Resources are released in reverse order of acquisition.
  3. Jumping backwards, by contrast, is how spaghetti starts.

Keywords and builtins used here

The run, in numbers

Lines
25
Characters to type
394
Tokens
137
Three-star pace
100 tpm

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

Type this snippet

Step 4 of 4 in Ownership & mistakes, step 18 of 25 in Pointers & memory.

← Previous Next →