Skip to content

Latest commit

 

History

History
115 lines (84 loc) · 2.93 KB

File metadata and controls

115 lines (84 loc) · 2.93 KB

Using the Memory Leak Tracker

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

Step 1: Write Your Code Normally

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.


Step 2: Prepare Your Project Files

  1. Put your C source (e.g. my_program.c or demo_allocs.c) in either:
    • examples/
    • src/
  2. Ensure src/leak_tracker.c and src/leak_tracker.h exist.

The Makefile expects to compile:

  • main.c (generated by run.sh), and
  • src/leak_tracker.c.

Step 3: Build and Run with run.sh

Make the script executable (if not already):

chmod +x run.sh

Then run:

./run.sh demo_allocs.c

run.sh performs the following:

  1. Searches only in examples/ and src/ for demo_allocs.c.
  2. Creates a temporary file main.c in the repo root by prepending:
    #include "leak_tracker.h"
    to the contents of your original file.
  3. Runs make clean and make, which does:
    • main.cmain.o
    • src/leak_tracker.csrc/leak_tracker.o
    • Links into leak_test_exec.
  4. Executes ./leak_test_exec, showing your program’s output and the memory‐leak report.
  5. Removes main.c, all object files, and leak_test_exec when done.

What It Detects

  • Memory Leaks – Blocks allocated but not freed by program exit.
  • Double‐Free Attempts – Calling free on the same pointer twice.
  • Invalid Free – Calling free on pointers not returned by malloc/calloc/realloc.

Sample Leak Report

===== 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 free on untracked pointers.
  • Leaked blocks – Remaining allocations not freed, with file/line info.