Memory Leaks in C
Every malloc borrows memory from the system. If you never free it, and lose the pointer to it, that memory stays "borrowed" until the program ends. This is a memory leak.
One small leak doesn't hurt. But a leak inside a loop, or in a server that runs for weeks, can eat all the RAM and crash the program. In this lesson you will learn the common causes of leaks, see them happen, and learn the habits and tools that prevent them.
What You Will Learn
- What a memory leak is.
- Why leaks are dangerous.
- Five common causes of leaks.
- How to count allocations to spot a leak.
- How to detect leaks with Valgrind and AddressSanitizer.
- Rules to avoid memory leaks.
What is a Memory Leak in C?
Exam definition: A memory leak occurs when dynamically allocated memory is not freed after use and the program loses every pointer to it, so the memory can never be released or reused while the program runs.
Memory trick: A leak is like borrowing library books and losing the receipt. The books are still issued in your name, nobody else can borrow them, and you can't return them because you don't know which ones they were. Borrow enough, and the library is empty.
Common Causes of Memory Leaks
/* 1. Forgetting to free */
int *p = malloc(100 * sizeof *p);
/* ... use p ... */
/* no free(p): leak */
/* 2. Overwriting the only pointer */
char *s = malloc(50);
s = malloc(80); /* first 50 bytes are lost */
/* 3. Returning early without freeing */
int *data = malloc(1000 * sizeof *data);
if (error)
return -1; /* leak: data never freed */
/* 4. Pointer goes out of scope */
void work(void)
{
int *tmp = malloc(40);
} /* tmp is gone, the 40 bytes are not */
/* 5. Freeing a struct but not what it points to */
struct student *st = malloc(sizeof *st);
st->name = malloc(30); /* if name is a char * member */
free(st); /* st->name's 30 bytes leak */
Why Memory Leaks are Dangerous
- Programs that run for a long time (servers, phones, embedded devices) keep growing until memory runs out.
- A leak inside a loop multiplies: 1 KB lost per request × 1 million requests = 1 GB.
- The system slows down (swapping) and finally malloc returns NULL or the program is killed.
- When a program ends, the operating system reclaims all its memory, so leaks hurt most in long-running programs. Still, freeing everything is a good habit and is expected in exams and interviews.
Example 1: Counting Allocations to Catch a Leak
Here, small wrapper functions count every allocation and free. If the counts don't match at the end, there's a leak.
#include <stdio.h>
#include <stdlib.h>
static int live_blocks = 0; /* allocated but not yet freed */
void *my_malloc(size_t size)
{
void *p = malloc(size);
if (p != NULL)
live_blocks++;
return p;
}
void my_free(void *p)
{
if (p != NULL)
{
live_blocks--;
free(p);
}
}
void leaky(void)
{
int *temp = my_malloc(10 * sizeof *temp);
temp[0] = 1; /* forgot my_free(temp) */
}
void clean(void)
{
int *temp = my_malloc(10 * sizeof *temp);
temp[0] = 1;
my_free(temp);
}
int main(void)
{
int i;
for (i = 0; i < 5; i++)
clean();
printf("After 5 clean() calls: %d block(s) leaked\n", live_blocks);
for (i = 0; i < 5; i++)
leaky();
printf("After 5 leaky() calls: %d block(s) leaked (%zu bytes)\n",
live_blocks, live_blocks * 10 * sizeof(int));
return 0;
}
Output
After 5 clean() calls: 0 block(s) leaked After 5 leaky() calls: 5 block(s) leaked (200 bytes)
Code Explanation
my_mallocincreases a counter on every successful allocation;my_freedecreases it.clean()allocates and frees, so the counter returns to 0.leaky()allocates but never frees. When it returns,tempdisappears, but the block stays allocated: lost forever.- Five calls leak 5 blocks of 40 bytes = 200 bytes. In a loop of a million calls, that would be about 40 MB.
- Real projects use the same idea in debug builds, or a leak-detection tool.
How to Detect Memory Leaks with Tools
Two free tools find leaks automatically and show the line that allocated the lost memory.
Valgrind (Linux):
gcc -g prog.c -o prog
valgrind --leak-check=full ./prog
... definitely lost: 200 bytes in 5 blocks
... at malloc ... by leaky (prog.c:22)
AddressSanitizer (GCC / Clang, Linux and macOS):
gcc -g -fsanitize=address prog.c -o prog
./prog
... ERROR: LeakSanitizer: detected memory leaks
... Direct leak of 40 byte(s) in 1 object(s) allocated from: ... leaky prog.c:22
Compile with -g so the tools can show file names and line numbers. On Windows, Visual Studio has a built-in leak checker.
Example 2: Fixing Leaks (Early Return and Nested Pointers)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
int roll;
char *name; /* points to separate heap memory */
};
struct student *new_student(int roll, const char *name)
{
struct student *s = malloc(sizeof *s);
if (s == NULL)
return NULL;
s->name = malloc(strlen(name) + 1);
if (s->name == NULL)
{
free(s); /* fix: free s before the early return */
return NULL;
}
strcpy(s->name, name);
s->roll = roll;
return s;
}
void delete_student(struct student *s)
{
if (s == NULL)
return;
free(s->name); /* inner memory first */
free(s); /* then the structure */
}
int main(void)
{
struct student *a = new_student(1, "Aarav Mehta");
struct student *b = new_student(2, "Diya Nair");
if (a == NULL || b == NULL)
{
delete_student(a); /* safe even if one is NULL */
delete_student(b);
return 1;
}
printf("%d %s\n", a->roll, a->name);
printf("%d %s\n", b->roll, b->name);
delete_student(a);
delete_student(b);
a = b = NULL;
printf("All memory released\n");
return 0;
}
Output
1 Aarav Mehta 2 Diya Nair All memory released
- Each student uses two blocks: the structure and its name. Both must be freed, inner first. If you freed
sfirst, you could no longer reachs->name. - When the second malloc fails, the function frees the first block before returning, fixing the early-return leak.
- Pairing
new_studentwithdelete_studentkeeps allocation and cleanup in one place.
Rules to Avoid Memory Leaks
- Every malloc/calloc must have a matching free.
- Decide who owns each pointer (who must free it).
- Free before re-pointing a pointer to new memory.
- On early returns and error paths, free what you allocated.
- Free inner allocations first (struct members, rows of a 2D array).
- Write create/destroy function pairs.
- Test with Valgrind or -fsanitize=address.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
| malloc inside a loop without free | Leak grows every iteration | Free at the end of each iteration |
p = malloc(...) twice | First block lost | Free before re-assigning |
free(s) before free(s->name) | Inner block leaks (and s->name is unreadable) | Free inner first |
p = realloc(p, n) failing | Old block leaks | Use a temp pointer |
| Thinking "the OS frees it anyway" in long programs | Server/app slowly runs out of memory | Free memory when you're done with it |
Memory Leak Practice Questions
- Define a memory leak.
- List four causes of memory leaks.
- Why are leaks more harmful in a server than in a short program?
- Name two tools that detect memory leaks.
- In what order should a structure and its pointer members be freed?
Show answers
- Heap memory that is not freed and to which every pointer is lost, so it can't be released while the program runs.
- Forgetting free; overwriting the only pointer; early return without free; pointer going out of scope; freeing a struct but not its pointed-to members (any four).
- A server runs for a long time, so leaked memory keeps adding up until RAM runs out; a short program's memory is reclaimed when it exits.
- Valgrind and AddressSanitizer (LeakSanitizer).
- Pointer members (inner memory) first, then the structure.
Coding Exercise
The function below leaks memory. Fix it so that every path frees what it allocated, and test it with a word that is found and one that isn't.
int contains(const char *text, const char *word)
{
char *copy = malloc(strlen(text) + 1);
strcpy(copy, text);
if (strstr(copy, word) != NULL)
return 1; /* leak */
return 0; /* leak */
}
Show solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int contains(const char *text, const char *word)
{
char *copy = malloc(strlen(text) + 1);
int found;
if (copy == NULL)
return 0;
strcpy(copy, text);
found = strstr(copy, word) != NULL;
free(copy); /* one free covers both outcomes */
return found;
}
int main(void)
{
printf("%d\n", contains("learn c programming", "c prog"));
printf("%d\n", contains("learn c programming", "java"));
return 0;
}
1 0
Quick Quiz: Memory Leaks (MCQ)
-
A memory leak happens when:
A) A pointer is NULL B) Allocated memory is never freed and its pointer is lost C) An array index is wrong D) A file is not closed
-
Which code leaks memory?
A)
p = malloc(4); free(p);B)p = malloc(4); p = malloc(8); free(p);C)free(NULL);D)int a[4]; -
Which tool detects memory leaks?
A) gcc -O2 B) Valgrind C) printf D) make
-
For a struct with a malloc'd name member, the correct order is:
A) free(s) then free(s->name) B) free(s->name) then free(s) C) Only free(s) D) Order doesn't matter
-
Leaks are most harmful in:
A) A program that runs for 1 second B) A server running for weeks C) Compile time D) Header files
Show answers
- B.
- B: the first 4-byte block is lost.
- B: Valgrind.
- B: inner member first.
- B: a long-running server.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Memory leak | Heap memory not freed and pointer lost |
|---|---|
| Main causes | No free, overwritten pointer, early return, scope ends |
| Worst in | Long-running programs and loops |
| Tools | Valgrind, -fsanitize=address |
| Nested memory | Free inner first, then the struct |
| Golden rule | One free per allocation |
Frequently asked questions
- What is a memory leak in C?
- Dynamically allocated memory that is never freed after the program loses its pointer, so it can't be reused.
- How do you avoid memory leaks?
- Match every malloc with one free, free on all exit paths, free before re-pointing, and test with Valgrind/ASan.
- Does the OS free leaked memory?
- Yes, when the program exits, but long-running programs can run out of memory before that.
Remember
- Leak = library books with a lost receipt.
- Borrow → use → return, on every path.
Next Topic
Next lesson: Dynamic Arrays in C. You will build 1D and 2D arrays whose size is decided at run time.