This guide shows how to use the memory leak detection wrapper provided in this repository. It assumes the following directory layout:
memory-leak-tracker/
├── docs/
├── examples/
│ └── demo_allocs.c
├── src/
│ ├── leak_tracker.c
│ └── leak_tracker.h
├── Makefile
└── run.sh
Do not manually add #include "leak_tracker.h" or modify your source.
Just write your C file as usual (e.g., demo_allocs.c):
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *p = malloc(20);
// forgot to free
printf("Hello, world!\n");
return 0;
}The run.sh script will automatically prepend #include "leak_tracker.h" behind the scenes when it creates main.c. This ensures the tracker wraps malloc, free, etc., without you changing your original file.
- Put your C source (e.g.
my_program.cordemo_allocs.c) in either:examples/src/
- Ensure
src/leak_tracker.candsrc/leak_tracker.hexist.
The Makefile expects to compile:
main.c(generated byrun.sh), andsrc/leak_tracker.c.
Make the script executable (if not already):
chmod +x run.shThen run:
./run.sh demo_allocs.crun.sh performs the following:
- Searches only in
examples/andsrc/fordemo_allocs.c. - Creates a temporary file
main.cin the repo root by prepending:to the contents of your original file.#include "leak_tracker.h"
- Runs
make cleanandmake, which does:main.c→main.osrc/leak_tracker.c→src/leak_tracker.o- Links into
leak_test_exec.
- Executes
./leak_test_exec, showing your program’s output and the memory‐leak report. - Removes
main.c, all object files, andleak_test_execwhen done.
- Memory Leaks – Blocks allocated but not freed by program exit.
- Double‐Free Attempts – Calling
freeon the same pointer twice. - Invalid Free – Calling
freeon pointers not returned bymalloc/calloc/realloc.
===== Memory Leak Report =====
Total malloc/calloc/realloc calls: 3
Total free calls: 2
Total bytes allocated: 52
Total bytes freed: 32
Invalid free attempts: 1
Leaked blocks:
Leak at 0x7ffee1f8c240: 20 bytes (allocated at main.c:14)
Summary: 1 block(s) leaked, total 20 byte(s) unfreed.
===== End of Report =====
- Total malloc/calloc/realloc calls – Count of all allocations.
- Total free calls – Count of free attempts.
- Invalid free attempts – Calls to
freeon untracked pointers. - Leaked blocks – Remaining allocations not freed, with file/line info.