C Programming Tutorial 0/65 lessons ~6 min read Lesson 40

    Memory Leaks

    A memory leak occurs when heap memory is allocated but never freed — program loses access while memory stays reserved.

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    A memory leak occurs when heap memory is allocated but never freed — program loses access while memory stays reserved.

    Understanding the topic

    Cause Missing free, lost last pointer to block.

    Detection valgrind --leak-check=full ./program

    Prevention Every malloc has exactly one free; use clear ownership.

    • Cause — Missing free, lost last pointer to block.
    • Detection — valgrind --leak-check=full .
    • Prevention — Every malloc has exactly one free; use clear ownership.

    Step-by-step explanation

    1. Cause — Missing free, lost last pointer to block.
    2. Detection — valgrind --leak-check=full .
    3. Prevention — Every malloc has exactly one free; use clear ownership.

    Informative example

    Example program:

    c
    #include <stdlib.h>
    void leak(void) {
    int *p = malloc(100 * sizeof(int));
    (void)p; /* never free(p) — leak */
    }

    Execution workflow

    1Memory Leaks — step by step
    1 / 3

    Cause

    Missing free, lost last pointer to block.

    Best practices

    • Enable warnings: gcc -Wall -Wextra -std=c11 source.c -o app
    • Give every variable a defined value before it is read.
    • Stay inside array bounds — C will not stop you from over-running a buffer.

    Common mistakes

    • Reading uninitialized storage — behavior is undefined.
    • Dismissing compiler warnings instead of fixing root causes.
    • Ignoring NULL returns from malloc, fopen, and similar APIs.

    Hands-on exercise

    Practice problems:

    • Fix a program with valgrind report
    • Free in error paths

    Summary

    Memory Leaks in C — Orphaned allocations and how to detect them.

    Ready to mark this lesson complete?Track your journey across the entire course.