C Academy · Lesson

Memory Leaks

Find and avoid leaks.

Lesson 3 of 413 steps

Memory Leaks is a free C Academy lesson on CoddyKit. This is lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C Academy learning path, and your progress syncs across the web and the CoddyKit app. The C Academy course includes 4 lessons in total.

What Is a Memory Leak

A memory leak happens when you allocate heap memory but never free it, and lose the only pointer to it.

The memory stays reserved until the program exits, wasting resources.

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

int main(void) {
    int *p = malloc(sizeof(int));
    *p = 5;
    printf("%d\n", *p);
    free(p);
    return 0;
}

Losing the Pointer

The classic leak overwrites a pointer with a new allocation before freeing the old one.

The first block becomes unreachable.

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

int main(void) {
    int *p = malloc(sizeof(int));
    free(p);
    p = malloc(sizeof(int));
    *p = 10;
    printf("%d\n", *p);
    free(p);
    return 0;
}

Leaks in Loops

Allocating inside a loop without freeing each iteration multiplies the leak quickly.

The fix is to free before the next iteration overwrites the pointer.

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

int main(void) {
    for (int i = 0; i < 3; i++) {
        int *p = malloc(sizeof(int));
        *p = i;
        printf("%d ", *p);
        free(p);
    }
    printf("\n");
    return 0;
}

Early Returns Leak

An early return after allocation can skip the cleanup. Always free on every exit path.

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

int process(int bad) {
    int *p = malloc(sizeof(int));
    if (bad) {
        free(p);
        return -1;
    }
    *p = 42;
    int r = *p;
    free(p);
    return r;
}

int main(void) {
    printf("%d\n", process(0));
    return 0;
}

The goto Cleanup Pattern

A single cleanup label reached by goto ensures one place frees everything, avoiding duplicated free calls.

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

int main(void) {
    int rc = 1;
    int *p = malloc(sizeof(int));
    if (!p) goto done;
    *p = 7;
    printf("%d\n", *p);
    rc = 0;
done:
    free(p);
    return rc;
}

Match Every Allocation

The simplest rule: for each malloc, calloc, or realloc, there must be exactly one corresponding free.

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

int main(void) {
    char *a = malloc(8);
    char *b = calloc(4, sizeof(char));
    a[0] = 'x';
    printf("%c %d\n", a[0], b[0]);
    free(a);
    free(b);
    return 0;
}

Freeing Nested Allocations

If a structure owns heap memory, free the inner pointers before freeing the outer block.

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

typedef struct {
    int *data;
} Box;

int main(void) {
    Box *b = malloc(sizeof(Box));
    b->data = malloc(3 * sizeof(int));
    b->data[0] = 1;
    printf("%d\n", b->data[0]);
    free(b->data);
    free(b);
    return 0;
}

Freeing an Array of Pointers

When you allocate an array of pointers and each entry is its own allocation, free every entry first, then the array.

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

int main(void) {
    int n = 3;
    int **rows = malloc(n * sizeof(int *));
    for (int i = 0; i < n; i++) {
        rows[i] = malloc(2 * sizeof(int));
        rows[i][0] = i;
    }
    for (int i = 0; i < n; i++) free(rows[i]);
    free(rows);
    printf("freed all rows\n");
    return 0;
}

Ownership Discipline

Decide who owns each allocation and is responsible for freeing it. Document this so callers know whether they must free a returned pointer.

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

char *make_greeting(void) {
    char *s = malloc(6);
    s[0]='h'; s[1]='i'; s[2]='\0';
    return s;
}

int main(void) {
    char *g = make_greeting();
    printf("%s\n", g);
    free(g);
    return 0;
}

Tools That Find Leaks

Tools like Valgrind and AddressSanitizer report leaks by tracking every allocation and showing which were never freed.

They are essential for verifying real programs.

A Clean Allocation Lifecycle

Putting it together: allocate, check, use, free on every path, and null the pointer. This keeps programs leak-free.

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

int main(void) {
    int *p = malloc(4 * sizeof(int));
    if (!p) return 1;
    for (int i = 0; i < 4; i++) p[i] = i + 1;
    int sum = 0;
    for (int i = 0; i < 4; i++) sum += p[i];
    printf("sum = %d\n", sum);
    free(p);
    p = NULL;
    return 0;
}

Quick Check

Test your understanding of memory leaks.

Recap

You learned to prevent memory leaks:

  • Match every allocation with exactly one free.
  • Free on every exit path, including early returns and errors.
  • Free nested and array-of-pointer allocations inner-first.
  • Define clear ownership and use tools like Valgrind to verify.
Free to start

Learn C with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
39
Lessons
144

Frequently Asked Questions

Is the “Memory Leaks” lesson free?

Yes — the full text of “Memory Leaks” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C Academy course, upgrade to CoddyKit PRO. The C Academy course includes 4 lessons in total.

What will I learn in “Memory Leaks”?

Find and avoid leaks. You practise C Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C Academy?

No prior experience is required. C Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Memory Leaks” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C Academy lesson?

Yes. Every C Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. malloc and free
  2. calloc and realloc
  3. Memory Leaks
  4. Dangling Pointers
← Back to C Academy