C Error Handling with goto
The goto-to-cleanup pattern is the idiomatic C approach for handling errors in functions that acquire multiple resources. Each failure jumps to a label that unwinds everything acquired so far, in reverse order. This is used extensively in the Linux kernel, OpenSSL, and other large C codebases.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/**
* Reads a line from a file, duplicates it into a heap buffer,
* uppercases it, and writes it to another file.
*
* Returns malloc'd string on success, NULL on error
* (with errno set and *errmsg populated).
*/
char *process_line(const char *in_path, const char *out_path, char **errmsg)
{
char *line = NULL; /* heap-allocated input line */
char *out_buf = NULL; /* heap-allocated uppercased output */
FILE *in_fp = NULL;
FILE *out_fp = NULL;
size_t cap = 0;
ssize_t len;
char *result = NULL; /* what we return on success */
*errmsg = NULL;
/* ---- Acquire resources, jumping to cleanup on failure ---- */
in_fp = fopen(in_path, "r");
if (!in_fp) {
*errmsg = strdup("failed to open input file");
goto cleanup;
}
out_fp = fopen(out_path, "w");
if (!out_fp) {
*errmsg = strdup("failed to open output file");
goto cleanup;
}
len = getline(&line, &cap, in_fp);
if (len < 0) {
*errmsg = strdup("failed to read line");
goto cleanup;
}
out_buf = malloc((size_t)len + 1);
if (!out_buf) {
*errmsg = strdup("out of memory");
goto cleanup;
}
for (ssize_t i = 0; i < len; i++)
out_buf[i] = (char)((line[i] >= 'a' && line[i] <= 'z')
? line[i] - ('a' - 'A')
: line[i]);
out_buf[len] = '\0';
if (fputs(out_buf, out_fp) == EOF) {
*errmsg = strdup("failed to write output");
goto cleanup;
}
/* Success: transfer ownership of out_buf to caller. */
result = out_buf;
out_buf = NULL;
cleanup:
/* ---- Release in reverse order of acquisition ---- */
free(out_buf);
free(line);
if (out_fp) fclose(out_fp);
if (in_fp) fclose(in_fp);
return result;
}Why the goto pattern is good here
free/fclose calls, and no risk of forgetting to release something.free(NULL) and fclose behind a null check are safe.out_buf into result and set out_buf = NULL before the label runs, so the cleanup code correctly frees nothing we intend to return. This is critical: if you return out_buf directly without nulling it, the free(out_buf) in cleanup would free it out from under the caller.goto cleanup jumps forward to the end of the function, never into a block. This is the only form of goto that avoids all the usual hazards (skipping initializers, jumping into loops, etc.).Key rules of thumb
goto is what produces spaghetti code.if (ptr) free(ptr) or rely on free(NULL) being safe; but guard fclose with if (fp).cleanup_mem:, cleanup_file:, …) unless cleanup itself can fail.