liveBook · Manning

Memory leak

As explained in Idiomatic Rust

A memory leak is a failure to release dynamically allocated memory after it is no longer reachable or needed.

A memory leak occurs when dynamically allocated heap memory remains unreleased after the pointer that addresses it goes out of scope. In C, returning from a function releases the pointer variable but not memory obtained with malloc(); free(a) must release it explicitly. section 4.1.1

Early return leaves an allocation behind

leaky_func allocates an integer, then returns when fopen fails. Because the error path skips free(a), the allocation leaks. The successful path closes the file and frees the memory. section 4.1.1

void leaky_func() {
    FILE *fp;
    int *a = malloc(sizeof(int));
    *a = 0;                           #1

    // try to open a file for reading
    fp = fopen("file.txt", "r");
    if (fp == NULL) {
        // there was an error!
        return;
    }

    // Now we can read from the file at fp.
    // ...

    fclose(fp);        #2
    free(a);           #3
}

Trace the allocation, failed file-opening branch, cleanup calls, and the missing free(a) on the early-return path. section 4.1.1

C++ addresses this hazard through constructors and destructors, with shared_ptr and ifstream shown as objects that support cleanup when control leaves the function. section 4.1.1

How Idiomatic Rust covers it

How deep it goes
Traces malloc, pointer scope, early returns, and free, then contrasts them with C++ cleanup objects.
Examples
Uses malloc(sizeof(int)), a failing fopen branch, free(a), shared_ptr<int>, and ifstream.
What you can do after
Diagnose leaks by matching every heap allocation with cleanup across all return paths.
How it connects
Connects memory leaks with heap allocation, pointers, scope, early returns, RAII, constructors, and destructors.

Also explained in

Compare how 5 books explain memory leak →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.