A cleanup path releases allocated memory before returning from success or error branches.

Cleanup Path

cleanup_path.c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int failAfterAlloc = ;
    int *buffer = (int *)malloc(sizeof(int));
    int status = 0;

    if (buffer == 0) {
        status = 1;
    } else if (failAfterAlloc) {
        status = 2;
    } else {
        *buffer = 7;
        status = *buffer;
    }

    if (buffer != 0) {
        free(buffer);
    }

    printf("status=%d\n", status);
    return 0;
}
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int failAfterAlloc = ;
    int *buffer = (int *)malloc(sizeof(int));
    int status = 0;

    if (buffer == 0) {
        status = 1;
    } else if (failAfterAlloc) {
        status = 2;
    } else {
        *buffer = 7;
        status = *buffer;
    }

    if (buffer != 0) {
        free(buffer);
    }

    printf("status=%d\n", status);
    return 0;
}
single cleanup One cleanup block can release resources after different branches set a status.
error branch Even when work stops early, allocated storage still needs to be released.