capypad
0 day streak
c / intermediate
Snippet

Clean Error Handling with goto

While often discouraged, using 'goto' for centralized resource cleanup is a common pattern in intermediate C (e.g., in the Linux kernel). it prevents deep nested if-statements and ensures that all opened resources are closed regardless of where an error occurs.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int process_file(const char *path) {
FILE *f = fopen(path, "r");
if (!f) return -1;
 
char *buffer = malloc(1024);
if (!buffer) {
goto cleanup_file;
}
 
// ... process file ...
 
free(buffer);
cleanup_file:
fclose(f);
return 0;
}
Breakdown
1
goto cleanup_file;
Jumps directly to the cleanup section to avoid leaking the file handle.
2
cleanup_file:
A label marking the start of the resource deallocation code.