Skip to content
systemcoding.dev
Systems Programming

Clean Up Resources on Error Paths with goto in C

Use the goto cleanup pattern in C to release files, memory and locks on every error path in reverse order, with a worked example and its limits.

7 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the C, GNU and Rust logos.

Every function that acquires more than one resource faces the same arithmetic. With three resources and a failure possible after each, there are four exit paths, and each must release exactly what has been acquired so far. Written with nested if statements, the function marches off the right margin. Written with early returns, each return repeats a different subset of cleanup, and the day someone adds a fourth resource, one of those subsets is wrong. The goto cleanup pattern fixes this with one list of labels that releases resources in reverse order. This post shows the pattern on Linux with glibc 2.41, and C11, explains why it is correct, and says when to use something else. It is also the style the Linux kernel documents in its coding style guide, in the section on centralized exiting of functions. The previous posts in this cluster covered errno and return-value checking.

The problem with early returns

Consider a function that opens a file, allocates a buffer and takes a lock. Here is the version most people write first.

early_return.cc
#include <fcntl.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

extern pthread_mutex_t table_lock;

int load_table(const char *path)
{
    int fd = open(path, O_RDONLY);
    if (fd == -1)
        return -1;

    char *buf = malloc(4096);
    if (!buf) {
        close(fd);
        return -1;
    }

    pthread_mutex_lock(&table_lock);
    ssize_t n = read(fd, buf, 4096);
    if (n == -1) {
        free(buf);          /* forgot pthread_mutex_unlock: deadlock later */
        close(fd);
        return -1;
    }
    pthread_mutex_unlock(&table_lock);

    free(buf);
    close(fd);
    return 0;
}

The read failure branch frees the buffer and closes the file but leaves the mutex locked. The next caller of load_table blocks forever. Nothing in the compiler's output points at it. The bug lives in a branch that runs only on an I/O error, which is exactly the branch tests rarely reach.

The goto pattern

The fix is to have one exit sequence and to jump into the right place in it. Each label undoes one acquisition, and the labels appear in the reverse order of acquisition. A failure after acquiring resource three jumps to the label that releases three, then falls through to the labels that release two and one.

Here is the same function with one exit sequence. Each failure records its error code in err and jumps to the label that releases what has been acquired so far.

goto_clean.cc
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

extern pthread_mutex_t table_lock;

int load_table(const char *path)
{
    int err = 0;
    int fd;
    char *buf;

    fd = open(path, O_RDONLY);
    if (fd == -1) {
        err = errno;
        goto out;
    }

    buf = malloc(4096);
    if (!buf) {
        err = ENOMEM;
        goto out_close;
    }

    pthread_mutex_lock(&table_lock);
    if (read(fd, buf, 4096) == -1) {
        err = errno;
        goto out_unlock;
    }

    /* success: fall through the cleanup labels with err == 0 */

out_unlock:
    pthread_mutex_unlock(&table_lock);
    free(buf);
out_close:
    close(fd);
out:
    errno = err;
    return err ? -1 : 0;
}

The structure follows three rules. Declare every resource at the top, or initialize it to a sentinel, so no label reads an uninitialized variable. Record the error code in err at the point of failure, before cleanup calls can overwrite errno. And end with a single block that sets errno and returns, so a caller sees the original cause, as the previous posts explained.

Calling load_table("/no/such/file") fails at open, jumps to out, skips every release, and returns -1 with errno equal to ENOENT. Calling it on a readable file runs straight through the labels in order, which is the success path: unlock, free, close.

Why the order of labels is the design

Each label is a place you can jump to, and the code below it runs. So a label's position says "everything from here down must happen if we got this far". That is why the labels read bottom to top as the reverse of acquisition: the lock was taken last, so its release is the first line you reach when you jump from the latest failure, and the file, taken first, is released last. Adding a fourth resource means adding one acquisition above and one label above out_unlock in the right place. No existing error path changes, which is the maintainability win over repeated cleanup in every branch.

A variant with one label

When all resources are initialized to a null or invalid value at the top, a single label that releases everything conditionally is simpler, and it tolerates any failure point. The cost is a test per resource, which for small functions is fine.

single_label.cc
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

int read_head(const char *path, char **out)
{
    int fd = -1;
    char *buf = NULL;
    int err = 0;

    fd = open(path, O_RDONLY);
    if (fd == -1) { err = errno; goto done; }

    buf = malloc(512);
    if (!buf) { err = ENOMEM; goto done; }

    if (read(fd, buf, 512) == -1) { err = errno; goto done; }

    *out = buf;
    buf = NULL;                 /* ownership moves to the caller */

done:
    if (fd != -1)
        close(fd);
    free(buf);                  /* free(NULL) is allowed */
    errno = err;
    return err ? -1 : 0;
}

Setting buf = NULL after handing it to the caller is the key line. It turns the final free into a no-op on success, so the same cleanup block serves both outcomes. free(NULL) is defined as doing nothing, which the C standard guarantees.

When not to use goto

  • Languages with destructors or defer. In C++ use RAII, in Go use defer, in Rust ownership. The pattern is a C idiom for a language with no scope-based cleanup, apart from the cleanup attribute covered in a later post.

  • Jumping into a block or past a variable-length array declaration. The C standard forbids jumping into the scope of a variable-length array, and jumping past an initialization is a bug. Declare variables before the first goto.

  • **Loops that need continue semantics.** A goto to a label inside the loop body is fine, but a label outside the loop that runs once per function is not a substitute for per-iteration cleanup.

  • Style rules that ban it. Some codebases do, such as MISRA C. Use nested scopes or small helper functions that return early, and accept the extra depth.

Testing every exit path

The point of the pattern is that every failure releases exactly what it should, and a test can check that claim by forcing each failure in turn. The simplest tool is a failure-injection wrapper: a counter that makes the Nth call to an allocation or system call fail on purpose. Run the function once with no injection to count how many failure points it has, then run it again for each point, and after every run confirm that nothing leaked.

In practice that means running the test under a leak checker. Build with -fsanitize=address,undefined using GCC 15 or Clang 20, which also reports a free of a pointer that was never allocated. For the descriptor and lock leaks that the sanitizer does not see, count open descriptors before and after the call by listing /proc/self/fd, and call pthread_mutex_trylock on the mutex afterwards: if it returns EBUSY the function left the lock held.

leakcheck.cc
#include <dirent.h>
#include <stdio.h>

int count_fds(void)
{
    DIR *d = opendir("/proc/self/fd");
    if (!d)
        return -1;
    int n = 0;
    while (readdir(d) != NULL)
        n++;
    closedir(d);
    return n - 3;       /* ".", ".." and the descriptor opendir itself uses */
}

Calling count_fds before and after load_table("/no/such/file") must give the same number, and the same must hold for every other failure point. If it does not, the cleanup chain has a hole, and the failing injection index tells you which label is missing a release.

Common mistakes with the pattern

Three errors account for most of the bugs in code that uses this idiom. The first is jumping to a label that releases a resource not yet acquired, which usually means the labels are in the wrong order or a variable was not initialized. The second is releasing twice, for example closing a descriptor in the failure path and again in the cleanup block, which closes a descriptor number another thread may have just received. The third is overwriting the error code during cleanup, which the err variable above prevents. When you review such a function, read the labels from the bottom and check each against the acquisitions from the top.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.