0 Tage Serie
c / intermediate
Snippet

Das Fehler-Cleanup-Muster mit goto

In C wird goto oft verwendet, um zu einem zentralen Cleanup-Block zu springen, damit Ressourcen ohne Code-Duplizierung freigegeben werden.

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;
}
Erklärung
1
goto cleanup_file;
Springt zum Label, wenn die Allokation fehlschlägt.
2
cleanup_file:
Label, das den Beginn der Ressourcen-Freigabe-Logik markiert.