Memory leaks

suggest change

A memory leak occurs when a program loses every usable pointer to an allocation without releasing it. Repeated leaks increase memory use and can eventually make later allocations fail.

void leak_one_buffer(void)
{
    char *buffer = malloc(4096);
    if (buffer == NULL) {
        return;
    }

    /* Use buffer. */

    /* Missing: free(buffer); */
}

Every allocation needs a clear owner and a cleanup path. In a function with several failure points, a single cleanup section can make that responsibility visible:

int process(void)
{
    int result = -1;
    char *input = malloc(4096);
    int *values = NULL;

    if (input == NULL) {
        goto cleanup;
    }

    values = malloc(100 * sizeof *values);
    if (values == NULL) {
        goto cleanup;
    }

    /* Use input and values. */
    result = 0;

cleanup:
    free(values);
    free(input);
    return result;
}

free(NULL) has no effect, so partially initialized cleanup like this is safe.

Some APIs allocate storage on behalf of the caller. Their documentation must state how that storage is released. POSIX getline, for example, can allocate or resize the buffer passed through its first argument; the caller owns that buffer and should normally reuse it across calls, then free it once after the loop.

An operating system commonly reclaims process resources at termination, but that does not make unbounded leaks acceptable in a long-running program or library. Explicit cleanup also helps leak detectors distinguish genuine ownership bugs. Very short command-line tools may intentionally rely on process teardown for final cleanup, but that should be a deliberate, documented choice.

Assigning NULL after free can prevent reuse through that one variable. It does not clear other aliases and is not a substitute for an ownership design.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents