goto & Cleanup Jumps in C
goto jumps to a same-function label unconditionally — the most powerful and most shunned control statement. Arbitrary backward jumps build spaghetti, but C kept goto respectable through one pattern: forward jumps to shared cleanup code. Acquire several resources, and on any failure goto the single block that releases whatever was obtained.
The Linux kernel uses this idiom pervasively. Rules that keep it safe: jump forward only, jump to cleanup only, never into blocks or over initializations (which the compiler forbids anyway).
Labels mark targets
cleanup: labels a spot; goto cleanup; jumps there — same function only, never across functions.
The cleanup pattern
Open file, allocate buffer, lock — each step's failure jumps to one exit block freeing everything acquired so far.
Forward only
Forward jumps to cleanup read as structured exits; backward jumps rebuild loops the language already provides.
Compiler guardrails
Jumping into a block's scope or over variable initializations is rejected — the remaining uses are the safe ones.
#include <stdio.h>#include <stdlib.h> int main(void) { int *buf = malloc(3 * sizeof *buf); if (!buf) goto fail; buf[0] = 7; printf("%d\n", buf[0]); free(buf); return 0;fail: fprintf(stderr, "out of memory\n"); return 1;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.