A function that acquires one resource is easy to get right: allocate, use, free. A function that acquires three, and can fail after each one, is where leaks come from. Each early return must free exactly what has been acquired so far, and no more. With three resources there are four exits, each with a different cleanup list, and when someone adds a fourth resource next month, every one of those lists must be updated. C has no destructors to do this automatically, so experienced C code uses a simple, auditable pattern instead: one cleanup block at the end of the function, reached from every exit.
Predict and run
This lesson uses one piece of syntax you have not needed yet. cleanup: is a label, a name followed by a colon, and goto cleanup; jumps straight to it. A goto can only jump within one function, and this course uses it for one pattern only: jumping forward to a single cleanup block.
Read the program before pressing Run. Write down its output and list what the cleanup block frees on each path.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *first = NULL;
int *second = NULL;
int status = 1;
first = malloc(sizeof *first);
if (first == NULL) { goto cleanup; }
second = malloc(sizeof *second);
if (second == NULL) { goto cleanup; }
*first = 20; *second = 30;
printf("%d\n", *first + *second);
status = 0;
cleanup:
free(second);
free(first);
return status;
}Check your prediction
50On success, both blocks exist and both are freed. If the first allocation fails, both pointers are still NULL, and free(NULL) does nothing. If the second fails, first is freed and free(second) does nothing. One block of code handles all three cases, because the pointers' values record what was acquired.
The version with early returns
Here is the same function written with a return at each failure:
int *first = malloc(sizeof *first);
if (first == NULL) { return 1; }
int *second = malloc(sizeof *second);
if (second == NULL) { return 1; } /* leaks first */The bug is easy to miss because the success path is correct, and a small allocation almost never fails on a development machine. Each new exit makes the next one harder to check. With a single cleanup label, a reviewer checks one list.
Fix: make every failure path leak-free
Here is that early-return version inside a whole program. tracked_alloc counts live blocks and can be told which allocation should fail, so the program can try every failure point in turn: none, the first, then the second. Run it, find the leak from the output alone, then rewrite make_pair with one cleanup path.
#include <stdio.h>
#include <stdlib.h>
static int live = 0; /* blocks allocated and not yet freed */
static int calls = 0;
static int fail_at = 0; /* make allocation number fail_at return NULL */
void *tracked_alloc(size_t bytes) {
++calls;
if (calls == fail_at) { return NULL; }
void *block = malloc(bytes);
if (block != NULL) { ++live; }
return block;
}
void tracked_free(void *block) {
if (block != NULL) { --live; free(block); }
}
/* Returns 0 on success, 1 on failure. Must release everything it allocated. */
int make_pair(void) {
int *first = tracked_alloc(sizeof *first);
if (first == NULL) { return 1; }
int *second = tracked_alloc(sizeof *second);
if (second == NULL) { return 1; }
*first = 25;
*second = 40;
printf("pair: %d %d\n", *first, *second);
tracked_free(second);
tracked_free(first);
return 0;
}
int main(void) {
for (int failing = 0; failing <= 2; ++failing) {
calls = 0;
fail_at = failing;
int result = make_pair();
printf("fail_at %d: result %d, live %d\n", failing, result, live);
}
return 0;
}pair: 25 40
fail_at 0: result 0, live 0
fail_at 1: result 1, live 0
fail_at 2: result 1, live 1Check your fix
Only the run where the second allocation fails ends with a live block: the early return 1 leaves first allocated. With both pointers starting at NULL, a default failure status and one cleanup label, every exit runs the same two frees:
#include <stdio.h>
#include <stdlib.h>
static int live = 0; /* blocks allocated and not yet freed */
static int calls = 0;
static int fail_at = 0; /* make allocation number fail_at return NULL */
void *tracked_alloc(size_t bytes) {
++calls;
if (calls == fail_at) { return NULL; }
void *block = malloc(bytes);
if (block != NULL) { ++live; }
return block;
}
void tracked_free(void *block) {
if (block != NULL) { --live; free(block); }
}
/* Returns 0 on success, 1 on failure. Must release everything it allocated. */
int make_pair(void) {
int status = 1;
int *first = NULL;
int *second = NULL;
first = tracked_alloc(sizeof *first);
if (first == NULL) { goto cleanup; }
second = tracked_alloc(sizeof *second);
if (second == NULL) { goto cleanup; }
*first = 25;
*second = 40;
printf("pair: %d %d\n", *first, *second);
status = 0;
cleanup:
tracked_free(second);
tracked_free(first);
return status;
}
int main(void) {
for (int failing = 0; failing <= 2; ++failing) {
calls = 0;
fail_at = failing;
int result = make_pair();
printf("fail_at %d: result %d, live %d\n", failing, result, live);
}
return 0;
}pair: 25 40
fail_at 0: result 0, live 0
fail_at 1: result 1, live 0
fail_at 2: result 1, live 0The three rules that make it work
- Initialize every resource to its "empty" value before the first jump. For pointers that is
NULL. Agotothat reachesfree(second)whilesecondis still uninitialized frees a garbage address, which is undefined behavior. Declaring all resources at the top, before anygoto, makes this automatic. - Default the result to failure.
status = 1at the start, and set to success only after the last step succeeds. A new failure path that forgets to set the status still reports failure. - Only jump forward, to the cleanup label. A
gotothat jumps backward or into the middle of a block is hard to follow. C also forbids jumping into the scope of a variable-length array, and jumping past an ordinary variable's initialization leaves it uninitialized.
Release in the reverse order of acquisition when one resource depends on another, such as a buffer that was filled from an open file.
Ownership transfer on success
Often a function builds something for its caller. Temporaries are freed on every path; the result is freed only on failure, and otherwise handed over. Setting the local to NULL after the hand-over makes "transferred" visible in the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int make_label(const char *topic, int minutes, char **out) {
int ok = 0;
char *number = NULL;
char *label = NULL;
number = malloc(16);
if (number == NULL) { goto cleanup; }
snprintf(number, 16, "%d", minutes);
size_t bytes = strlen(topic) + 1 + strlen(number) + 1;
label = malloc(bytes);
if (label == NULL) { goto cleanup; }
snprintf(label, bytes, "%s:%s", topic, number);
*out = label;
label = NULL;
ok = 1;
cleanup:
free(label);
free(number);
return ok;
}
int main(void) {
char *label = NULL;
if (!make_label("reading", 25, &label)) { return 1; }
printf("%s\n", label);
free(label);
return 0;
}reading:25On success, label = NULL means the cleanup block's free(label) does nothing, and the caller owns the string. On failure, the caller's *out was never written.
How the project uses it
The project's main calls analyzer_init first, so the analyzer is in its empty state before any jump can happen. exit_code starts at 1 and becomes 0 only after the report and the final ferror(stdout) check succeed. Every failure, whether out of memory, a read error or report storage, jumps to cleanup:, which calls analyzer_destroy. Destroy resets the fields after releasing, so calling it twice is safe in this API. That safety does not extend to copies of the struct, which would still hold the old pointer.
Practice
Your turn
Write int join_topics(const char *a, const char *b, char **out). It makes a heap copy of each topic, rejects the call if either copy is empty, then builds a new string a+b, stores it in *out and returns 1. Use one cleanup label: the two copies are freed on every path, and *out is written only on success. Expected output: joined: reading+coding, empty second: rejected, out still NULL.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *copy_text(const char *text) {
size_t bytes = strlen(text) + 1;
char *copy = malloc(bytes);
if (copy != NULL) { memcpy(copy, text, bytes); }
return copy;
}
/* Write join_topics here. */
int main(void) {
char *joined = NULL;
if (join_topics("reading", "coding", &joined)) {
printf("joined: %s\n", joined);
free(joined);
joined = NULL;
}
if (!join_topics("reading", "", &joined)) {
printf("empty second: rejected, out still %s\n", joined == NULL ? "NULL" : "set");
}
return 0;
}Hint 1: the idea
There are three resources: two copies and the result. A validation failure after the copies exist is just another goto cleanup, and the cleanup block does not need to know which step failed.
Hint 2: a first step
Declare every resource at the top, initialized so that the cleanup block is safe to run before any of them exists. Write the cleanup block next, then the first copy with its goto, and run the success case before adding the rest.
Show one solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *copy_text(const char *text) {
size_t bytes = strlen(text) + 1;
char *copy = malloc(bytes);
if (copy != NULL) { memcpy(copy, text, bytes); }
return copy;
}
int join_topics(const char *a, const char *b, char **out) {
int ok = 0;
char *left = NULL, *right = NULL, *result = NULL;
size_t bytes = 0;
left = copy_text(a);
if (left == NULL) { goto cleanup; }
right = copy_text(b);
if (right == NULL) { goto cleanup; }
if (left[0] == '\0' || right[0] == '\0') { goto cleanup; }
bytes = strlen(left) + 1 + strlen(right) + 1;
result = malloc(bytes);
if (result == NULL) { goto cleanup; }
snprintf(result, bytes, "%s+%s", left, right);
*out = result;
result = NULL;
ok = 1;
cleanup:
free(result);
free(right);
free(left);
return ok;
}
int main(void) {
char *joined = NULL;
if (join_topics("reading", "coding", &joined)) {
printf("joined: %s\n", joined);
free(joined);
joined = NULL;
}
if (!join_topics("reading", "", &joined)) {
printf("empty second: rejected, out still %s\n", joined == NULL ? "NULL" : "set");
}
return 0;
}joined: reading+coding
empty second: rejected, out still NULLThe rejected call jumps to cleanup with both copies allocated and frees them, so it leaks nothing. bytes is declared with the pointers at the top, as rule 1 says. In make_label above, bytes is declared after the first goto; C allows jumping past an ordinary declaration, but the variable is then uninitialized at cleanup:, which is harmless only because the cleanup block never reads it. Declaring everything first removes the need for that reasoning. The temporaries make this example a little artificial, but the shape is exactly what larger functions need. Next, you will make these failure paths run on demand in a test.
Completion is saved in this browser only. It does not measure mastery.