0 day streak
c / intermediate
Snippet

The Error-Cleanup Pattern with goto

In C, goto is often used to jump to a single cleanup block, ensuring resources are freed without duplicating code in multiple error checks.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <stdlib.h>
int process_file(const char *path) {
FILE *f = fopen(path, "r");
if (!f) return -1;
char *buf = malloc(1024);
if (!buf) {
goto cleanup_file;
}
// ... processing ...
free(buf);
fclose(f);
return 0;
cleanup_file:
fclose(f);
return -1;
}
Breakdown
1
goto cleanup_file;
Jumps to the label if allocation fails.
2
cleanup_file:
Label defining the start of the resource cleanup logic.