0 day streak
c / intermediate
Snippet

Unified Error Cleanup with goto

In systems programming, using 'goto' for a single exit point is an accepted pattern to ensure all allocated resources are freed consistently, avoiding deeply nested conditional logic.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdlib.h>
void process_data() {
int *data = malloc(1024);
if (!data) return;
if (/* some error condition */ 1) {
goto cleanup;
}
// ... more logic ...
cleanup:
free(data);
}
Breakdown
1
goto cleanup;
Jumps directly to the cleanup label, skipping the remaining function logic.
2
cleanup:
A label acting as a target for the jump, usually placed at the end of the function.