On this page
  1. Error Handling & goto cleanup
  2. Contents
  3. Single-Exit goto cleanup Pattern
  4. Return Codes & errno

Error Handling & goto cleanup

Prev: Memory Layout, Alignment & Qualifiers | Up: compilation_and_internals | Next: tutorials
Rel: Error-Handling Philosophies, stdio.h & File I/O
Ref: cppreference — errno
Tags: #public #prog #c #internals #errors


Contents


Single-Exit goto cleanup Pattern

Because C has no exceptions or destructors, the idiomatic way to prevent leaks across multi-resource functions is initializing every resource handle to NULL and jumping to a single cleanup: label on error:

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

int process_file(const char *path) {
    int rc = -1;
    FILE *fp = NULL;
    char *buf = NULL;

    fp = fopen(path, "rb");
    if (!fp) goto cleanup;

    buf = malloc(4096);
    if (!buf) goto cleanup;

    /* ... work with fp and buf ... */
    rc = 0;

cleanup:
    free(buf);
    if (fp) fclose(fp);
    return rc;
}

Return Codes & errno

Return 0 on success and negative error codes (or a typed enum Status) on failure; inspect errno only immediately after a standard library call reports failure.

Linked from

Related notes