Skip to content
Tutorials Center
My learning

Topics

Lesson 108 of 135 ยท Advanced C

Error Handling with goto (the Cleanup Pattern)

Use goto for structured cleanup in C. Learn the single-exit and cleanup-ladder patterns, compare them with nested ifs, and test every failure path.

goto has a bad reputation, and for jumping around inside loops it is deserved. But there is one job where experienced C programmers reach for it on purpose: releasing resources when a function fails halfway through. The Linux kernel, SQLite, PostgreSQL and many other large C codebases use it for exactly that.

Error Handling showed a first example with one cleanup label. This lesson goes further. You'll see why the problem exists, the two standard patterns (a single cleanup block and a "ladder" of labels), what the alternatives cost, and how to test every failure path so that no leak hides in code that normally never runs.

The problem: many resources, many exits

Imagine a function that creates a session: it allocates a struct, then a buffer, then a name string. Any step can fail, and when step three fails you must undo steps one and two, but not step four, which never happened. Written with early returns, the cleanup code multiplies:

C
struct session *session_new(const char *name)
{
    struct session *s = malloc(sizeof *s);
    if (s == NULL) return NULL;

    s->buffer = malloc(1024);
    if (s->buffer == NULL) { free(s); return NULL; }

    s->name = strdup(name);
    if (s->name == NULL) { free(s->buffer); free(s); return NULL; }
    return s;
}

Each new resource adds a line to every earlier failure branch. Forget one and you leak memory, and nobody notices because the failing branch rarely runs.

Pattern 1: one cleanup block

If the function acquires resources that are always released at the end (a file handle, a temporary buffer), start every pointer at NULL, jump to one label on failure, and release everything there. Releasing NULL is harmless for free, so the block needs no bookkeeping. The same block runs on success and on failure:

C One exit point with goto cleanup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The temporary buffer tmp is freed on all three paths, and result is only set when everything succeeded. Notice the pattern: initialize every resource to a "nothing acquired" value, acquire in order, and make the cleanup block safe for any subset.

Pattern 2: the cleanup ladder

A single block does not fit when the function should keep the resources on success (as session_new must). Then you need a ladder of labels, one per acquired resource, stacked in reverse order. A failure jumps to the label that releases everything acquired so far, and execution falls through the remaining labels like water running down steps.

C A cleanup ladder with test hooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Read the ladder bottom-up. If step 3 fails, execution jumps to fail_free_buffer, frees the buffer, falls through to free the session, and returns NULL. Step 2 failing enters one rung lower; step 1 failing enters at the bottom. The labels appear in reverse order of acquisition, so the code matches the mental model "undo the last thing first". The live_allocations counter shows the test result: after every failure scenario the number returns to zero, and in the success case it reads 3 until session_free releases everything.

Tip: Name labels after what they free (fail_free_buffer, out_close_file), not after numbers (err3). When you add a fourth resource, the label names tell you exactly where it belongs.

The alternatives, and what they cost

Approach Strength Weakness
Early return with repeated cleanup Easy to read for two resources Cleanup is duplicated; every new resource touches every earlier branch
Nested if (ok) { ... } No goto at all The "success path" drifts to the right; deep pyramids
Status flag in a long && chain Compact Hard to debug; resources and conditions mix
goto cleanup (block or ladder) Linear success path, each release written once Needs discipline with labels; reviewers must know the idiom

None of these is wrong in a small function. The goto idiom pays off as the number of resources grows, because the success path stays flat and the cleanup is written once per resource. Compilers also generate efficient code for it, since it compiles to plain jumps. (Other languages hide the same thing behind defer, finally or destructors; C asks you to write it out.)

Rules that keep goto safe

Using goto for cleanup works because the rules are strict:

  1. Only jump forward, to a label near the end of the function. Never use it for loops.
  2. Never jump over a variable's initialization that the target code uses. In C a jump past a declaration is allowed, but the variable is then uninitialized. Declare resource pointers at the top and set them to NULL.
  3. Do not jump into the scope of a variable-length array. The compiler rejects it.
  4. Never free something twice. After releasing a pointer that remains in scope, set it to NULL if another path might release it again.
  5. Keep one cleanup per function. If a function needs several independent cleanup sections, it is probably doing too much; split it.
  6. Check the cleanup operations that can fail, such as fclose on a file you wrote to, and propagate the failure through the return value.

A label must be followed by a statement. In C23 a label can precede a declaration, but earlier standards need an empty statement (;) first. Placing the label before a plain statement such as a function call avoids the problem.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why initialize every pointer to NULL before the first goto?

    A jump can skip later allocations. If those pointers are NULL, free(NULL) is a harmless no-op and the cleanup block works for any failure point.
  2. 2. In a cleanup ladder, in which order are the labels written?

    Reverse order lets execution fall through from the point of failure, releasing the most recent resource first, down to the first.
  3. 3. When is a single cleanup block (instead of a ladder) enough?

    If everything is always released at the end, one block works for all outcomes. A ladder is needed when success keeps some resources alive for the caller.
  4. 4. Which use of goto is considered acceptable in C?

    Forward jumps to a cleanup section are the standard idiom. Backward jumps hurt readability, and goto cannot leave the current function anyway.

Summary

  • Functions that acquire several resources need one place that releases them; repeating cleanup at every return is error-prone.
  • Single cleanup block: initialize resources to NULL, goto cleanup on failure, release everything there; it runs on success too.
  • Cleanup ladder: stack labels in reverse order of acquisition so a failure enters at the right rung and falls through the rest; use it when success keeps resources for the caller.
  • Jump forward only, never over needed initializations, and name labels after what they release.
  • Test failure paths with injected failures and a counter, so leaks in rarely used code show up.

Next: Embedded C Basics, where memory and resources are tighter than ever.