The user wants a memory leak detector implemented in C for Linux user-space applications.
1. Scope and Requirements:
- Target: Linux user-space.
- Language: C.
- Goal: Detect memory leaks (allocations without corresponding frees).
- Mechanism: Need to intercept standard allocation functions (
malloc, calloc, realloc, free).
2. High-Level Design:
- Interception: How do we wrap
malloc?
- Option A: Macro redefinition (
#define malloc(x) my_malloc(x)). Simple, but has issues with standard library internals or if pointers to functions are used.
- Option B: LD_PRELOAD with shared library. This is the standard "hacker/power user" way on Linux. We create a shared object (
.so) that defines symbols malloc, free, etc. The dynamic linker will prefer these over the ones in libc.so.
- Tracking: Inside
my_malloc, we need to:
- Perform the actual allocation (calling the real
malloc).
- Record metadata (pointer, size, call stack).
- Store this in a data structure (hash map or linked list).
- Reporting: Inside
my_free, we need to:
- Look up the pointer.
- Remove it from the tracking structure.
- Call the real
free.
- Output: On program exit (
atexit or destructors), dump the list of remaining allocations.
3. Detailed Implementation Steps:
4. Drafting the Code (Mental or Scratchpad):
-
Header: dlfcn.h, stdio.h, stdlib.h, execinfo.h, pthread.h.
-
Real pointers:
static void* (*real_malloc)(size_t) = NULL;
static void (*real_free)(void*) = NULL;
static void* (*real_calloc)(size_t, size_t) = NULL;
static void* (*real_realloc)(void*, size_t) = NULL;
-
Init function: dlsym all of these.
-
The Hook:
void* malloc(size_t size) {
if (!real_malloc) init();
// Check recursion (in case init calls malloc)
// Call real_malloc
// Log info
// Return ptr
}
-
The "Calloc" Problem: dlsym sometimes calls calloc (specifically in older glibc or depending on config). This causes a bootstrap loop.
- Fix: If
calloc is called before init is complete, return a static buffer or a dummy pointer (risky) or handle the specific request dlsym makes. Often dlsym requests 1 element of size X.
- Better Fix: Just provide a temporary static buffer for the very first allocation.
-
Storage:
Let's use a simple linked list.
Struct: { void* ptr; size_t size; void* frames[10]; int frame_count; struct Node* next; }.
Where to store this struct?
- Approach A:
real_malloc space before the returned pointer (creating an internal header).
- Approach B: A separate mapping.
- Approach A is best for locality and simplicity. We allocate
size + sizeof(Header).
- Wait, if we modify the pointer returned,
realloc and free get the user pointer. We need to get the real pointer back. ptr - sizeof(Header).
5. Refining the Approach (Header-based interception):
malloc:
real_malloc(size + HEADER_SIZE)
- Fill header (size, backtrace).
- Return
ptr + HEADER_SIZE.
free:
- Input
ptr.
real_ptr = ptr - HEADER_SIZE.
real_free(real_ptr).
- Wait, tracking leaks requires persistence. If we free it, it's not a leak. We don't need a central list for the lifetime of the allocation, only for reporting at the end.
- Correction: To report leaks, we need a list of active allocations.
- So, in
malloc: Add to global list.
- In
free: Remove from global list.
- This brings back the problem: "How do I allocate the list node?"
- Solution: Use the "Header" approach. The tracking info is embedded in the allocation block itself.
- But we need to find the block in the list during
free. If we use a linked list, we need pointers.
- Trick: The header contains
prev and next pointers. The global list holds references to headers.
- Double Linked List in Header:
struct AllocInfo { size_t size; void* frames[...]; struct AllocInfo *prev, *next; }
malloc: real_malloc(size + sizeof(Info)). Fill info. Add to global list. Return ptr + sizeof(Info).
free: info = ptr - sizeof(Info). Remove from global list. real_free(info).
6. Addressing Edge Cases:
7. Structuring the Solution:
- Part 1: The Code. A single
.c file that compiles to a .so.
- Part 2: Compilation Instructions.
gcc -shared -fPIC -ldl -o leak_detector.so ...
- Part 3: Usage.
LD_PRELOAD=./leak_detector.so ./your_app
- Part 4: Explanation. How it works (dlsym, LD_PRELOAD, headers, backtraces).
8. Writing the Code Details (Mental Draft):
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <execinfo.h>
#include <pthread.h>
#include <unistd.h>
// Function pointers
static void* (*real_malloc)(size_t) = NULL;
static void (*real_free)(void*) = NULL;
// ...
// Thread local recursion guard
__thread int in_hook = 0;
// Header for tracking
typedef struct alloc_info {
size_t size;
struct alloc_info *next;
struct alloc_info *prev;
void *callers[MAX_DEPTH];
int caller_count;
} alloc_info_t;
static alloc_info_t *head = NULL;
static pthread_mutex_t list_lock = PTHREAD_MUTEX_INITIALIZER;
void init() {
real_malloc = dlsym(RTLD_NEXT, "malloc");
real_free = dlsym(RTLD_NEXT, "free");
// ...
}
// The "Calloc" bootstrap issue
// We need a static buffer for the very first allocation dlsym might do.
static char temp_buffer[4096];
static int temp_used = 0;
void* malloc(size_t size) {
if (real_malloc == NULL) {
// We are likely in the middle of dlsym initialization
// Or this is the very first call.
if (temp_used + size < 4096) {
void* p = temp_buffer + temp_used;
temp_used += size;
return p;
}
// Fallback - should not happen if bootstrap is small
init();
if (real_malloc == NULL) return NULL; // catastrophe
}
if (in_hook) return real_malloc(size);
in_hook = 1;
// Allocation logic
alloc_info_t *info = real_malloc(size + sizeof(alloc_info_t));
// fill info...
// add to list...
in_hook = 0;
return (void*)(info + 1);
}
Wait, dlsym usually calls calloc, not malloc. I need to hook calloc specifically with the static buffer logic.
Actually, just hooking calloc with a check if (!real_malloc) is safer.
9. Refining the Output:
The output should go to a file or stderr. On atexit, iterate the list, print addresses. Use addr2line later or backtrace_symbols_fd.
Note: backtrace_symbols allocates memory. Can't use it inside malloc hook (recursion). We must store raw pointers in the header and print them later. During atexit, we can call backtrace_symbols because we are not hooking any more (or we can just print hex).
Let's stick to printing raw hex addresses. It's the most robust way. I will add a script helper to decode them.
10. Final Code Structure:
- Includes & Defines.
- Function pointers.
- Data structures (Double linked list embedded in allocation).
dlsym initialization helper.
malloc wrapper (Handle bootstrap, handle recursion, allocate with header, record stack, link list).
free wrapper (Unlink list, real free).
calloc wrapper (Handle bootstrap dlsym requirement).
atexit handler (Iterate list, print leaks).
Let's review the realloc case. It's tricky.
realloc(ptr, size):
- Find header
ptr - sizeof(header).
- Unlink old.
real_realloc(header, size + sizeof(header)).
- Relink new.
- Return new user ptr.
If
ptr is NULL, act like malloc.
If size is 0, act like free.
I'll skip realloc implementation details in the code to keep it concise, or just implement a naive version. Implementing realloc correctly with the header offset logic is complex but necessary for a "real" detector. I'll try to include it for completeness.
Self-Correction on realloc:
If I move the block, the prev and next pointers in the neighbors need to stay valid, but the current block's pointers are fine. If real_realloc moves the block, the header is moved too. I just need to update the list pointers.
Wait, the list pointers are inside the moved block. The neighbors point to the old address.
So:
info = ptr - offset.
real_info = real_realloc(info, size + offset).
- If
real_info != info:
- I must update
real_info->prev->next and real_info->next->prev.
- This requires locking.
- It's easier to
Unlink(info), Realloc, Link(real_info).
Final Plan:
- Concept: Use
LD_PRELOAD to override libc memory functions.
- Tracking: Embed a header structure in every allocation storing size and backtrace pointers. Maintain a doubly-linked list of these headers.
- Bootstrap: Handle
dlsym calling calloc using a static buffer.
- Recursion: Use
__thread variable to detect re-entry.
- Reporting: An
atexit handler iterates the list and prints remaining blocks.
Let's write the C code.
Warning about backtrace:
Calling backtrace() inside malloc can be risky if backtrace calls malloc.
However, backtrace generally uses mmap or stack allocations.
To be safe: if (in_hook) return real_malloc(size); -> This prevents tracking the tracking-logic's own memory, which is fine.
Warning about dlsym:
dlsym(RTLD_NEXT, "malloc") might allocate.
If I call dlsym inside malloc, and dlsym calls malloc, I loop.
So dlsym must be called once, lazily, or inside calloc (the likely culprit).
Standard pattern:
Lazy init real_malloc.
If real_malloc is null in malloc:
Call dlsym.
If dlsym calls malloc again, real_malloc is still null. Infinite loop.
Solution: A initializing flag.
If initializing is true, return temp buffer (if possible) or NULL.
Let's refine the calloc bootstrap. It's the specific one that usually bites.
dlsym -> calloc.
So calloc checks: if !real_calloc, return a chunk of static memory.
Output format:
LEAK: 0x... size=100
[0] ./prog(+0x...) [0x...]
User can use addr2line -e ./prog 0x... to find line.
Implementation Constraints:
- Must handle thread safety (
pthread_mutex_t).
- Must handle recursion.
Let's proceed with generating the C code.
One final check: realloc(NULL, size) should work like malloc. realloc(ptr, 0) should work like free. realloc(ptr, size) changes size.
I will implement the logic robustly.
Code skeleton:
#define _GNU_SOURCE
#include <stdio.h>
// ... includes
// Typedefs for real functions
typedef void* (*malloc_t)(size_t);
typedef void (*free_t)(void*);
typedef void* (*calloc_t)(size_t, size_t);
typedef void* (*realloc_t)(void*, size_t);
static malloc_t real_malloc = NULL;
static free_t real_free = NULL;
static calloc_t real_calloc = NULL;
static realloc_t real_realloc = NULL;
// Recursion guard
static __thread int hook_active = 0;
// List
static mem_block_t *head = NULL;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
// Temp buffer for dlsym bootstrap
static char temp_mem[4096];
static size_t temp_pos = 0;
// Init
void init_hooks() {
if (!real_malloc) {
real_malloc = dlsym(RTLD_NEXT, "malloc");
real_free = dlsym(RTLD_NEXT, "free");
real_calloc = dlsym(RTLD_NEXT, "calloc");
real_realloc = dlsym(RTLD_NEXT, "realloc");
}
}
// Malloc
void* malloc(size_t size) {
if (hook_active) {
return real_malloc(size);
}
// Init check
if (!real_malloc) {
// Handle bootstrap using temp_mem
// ...
}
hook_active = 1;
// Allocate with header
mem_block_t *block = real_malloc(size + sizeof(mem_block_t));
// Fill header, backtrace, add to list
// ...
hook_active = 0;
return (void*)(block + 1);
}
Wait, dlsym calling calloc is the main issue.
Inside calloc:
void* calloc(size_t nmemb, size_t size) {
if (!real_calloc) {
// Try to init?
// dlsym might be calling us.
// Return temp buffer.
size_t total = nmemb * size;
void* p = temp_mem + temp_pos;
temp_pos += total;
return p;
}
// Normal logic...
}
This looks solid. I will assemble the complete C code and the usage instructions.
One detail: addr2line requires the binary to be unstripped. I should mention that.
Also, backtrace_symbols_fd is async-signal-safe but might allocate. backtrace is fine. I will store pointers and print hex.
Structure of the Answer:
- Introduction: Briefly explain
LD_PRELOAD and the mechanism.
- The C Code: Complete, compile-able source.
- Compilation:
gcc command.
- Usage: How to run the target app.
- Interpreting Results: How to use
addr2line.
I will focus on malloc, free, and calloc. realloc is important but adds complexity. I will include realloc for a good solution.
Recursion Guard logic:
The hook_active flag is thread-local (__thread). This is crucial because one thread might be inside the hook (allocating list structures) while another thread calls malloc.
Memory Management of the List:
We are embedding the list node inside the allocated block.
UserPtr = HeaderPtr + 1.
When free(UserPtr) is called:
HeaderPtr = UserPtr - 1.
This works perfectly.
Corner case: dlsym fails? Unlikely, but handle NULL return from real_malloc.
Final Polish of the Code:
Add comments explaining the "Bootstrap" and the "Recursion" logic. Ensure headers are correct.
(Self-Correction during coding): backtrace might call malloc on some systems (though rare, usually mmap). If it does, we have infinite recursion.
The hook_active guard handles this. If backtrace calls malloc, hook_active is 1, so we just pass through to real_malloc. We won't get a stack trace for that internal allocation, but we won't crash.
Let's write it.
This is a complete implementation of a memory leak detector for Linux using LD_PRELOAD.
The Concept
The detector works by intercepting calls to standard memory functions (malloc, free, calloc, realloc) using the Linux dynamic linker's LD_PRELOAD feature.
- Interception: We define our own
malloc functions in a shared library (.so). When the application runs, the loader prefers our functions over the ones in libc.
- Tracking: Inside our
malloc, we call the real malloc (via dlsym) to get memory. We then add a "shadow header" to this memory block to store metadata (size, call stack).
- Reporting: We track all active allocations in a linked list. When the program exits, we iterate through this list and print any allocations that were never freed.
1. The Source Code (leak_detector.c)
Save the following code to a file named leak_detector.c.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include <execinfo.h>
#include <pthread.h>
#include <unistd.h>
#include <link.h>
// ============================================================================
// Configuration
// ============================================================================
#define BT_BUF_SIZE 64 // Max depth of backtrace
// ============================================================================
// Data Structures
// ============================================================================
// A linked list node to track every active allocation
typedef struct allocation_info {
void *real_ptr; // Pointer returned by real malloc (points to our header)
void *user_ptr; // Pointer given to the user
size_t size; // Size requested by user
void *backtrace[BT_BUF_SIZE]; // Call stack symbols
int backtrace_size; // Number of frames captured
struct allocation_info *next;
} alloc_info_t;
// Global state
static alloc_info_t *head = NULL;
static pthread_mutex_t list_mutex = PTHREAD_MUTEX_INITIALIZER;
static int is_initialized = 0;
static int in_hook = 0; // Prevent recursive hooking during initialization
// Function pointers to the real libc functions
static void* (*real_malloc)(size_t) = NULL;
static void (*real_free)(void*) = NULL;
static void* (*real_calloc)(size_t, size_t) = NULL;
static void* (*real_realloc)(void*, size_t) = NULL;
// Temporary bootstrap buffer for dlsym (dlsym might call calloc)
static char bootstrap_buffer[8192];
static size_t bootstrap_offset = 0;
// ============================================================================
// Initialization
// ============================================================================
static void init_hooks() {
if (is_initialized) return;
// Set hook flag to prevent recursion during dlsym
in_hook = 1;
real_malloc = dlsym(RTLD_NEXT, "malloc");
real_free = dlsym(RTLD_NEXT, "free");
real_calloc = dlsym(RTLD_NEXT, "calloc");
real_realloc = dlsym(RTLD_NEXT, "realloc");
if (!real_malloc || !real_free || !real_calloc || !real_realloc) {
const char *err = "LEAK_DETECTOR: Failed to resolve libc symbols.\n";
write(STDERR_FILENO, err, strlen(err));
_exit(1);
}
is_initialized = 1;
in_hook = 0;
atexit(report_leaks);
}
// ============================================================================
// Allocation Tracking Logic
// ============================================================================
static void add_allocation(void *user_ptr, size_t size) {
if (!is_initialized) return;
// Capture the stack trace
void *buffer[BT_BUF_SIZE];
int nptrs = backtrace(buffer, BT_BUF_SIZE);
// Create the tracking node
// Note: We use real_malloc here to avoid recursive loops
alloc_info_t *info = real_malloc(sizeof(alloc_info_t));
if (!info) return; // Out of memory
info->user_ptr = user_ptr;
info->size = size;
memcpy(info->backtrace, buffer, nptrs * sizeof(void*));
info->backtrace_size = nptrs;
// Add to linked list (thread-safe)
pthread_mutex_lock(&list_mutex);
info->next = head;
head = info;
pthread_mutex_unlock(&list_mutex);
}
static void remove_allocation(void *user_ptr) {
if (!is_initialized || !user_ptr) return;
pthread_mutex_lock(&list_mutex);
alloc_info_t *curr = head;
alloc_info_t *prev = NULL;
while (curr != NULL) {
if (curr->user_ptr == user_ptr) {
if (prev == NULL) {
head = curr->next;
} else {
prev->next = curr->next;
}
// Free the tracking node using real_free
real_free(curr);
pthread_mutex_unlock(&list_mutex);
return;
}
prev = curr;
curr = curr->next;
}
// If we get here, we freed something that wasn't in our list
// (or double free, or we didn't track the malloc for some reason)
pthread_mutex_unlock(&list_mutex);
}
// ============================================================================
// Reporting
// ============================================================================
void report_leaks() {
// If we are reporting, we want to stop intercepting to avoid messing up output buffers
is_initialized = 0;
char buf[512];
int len;
len = snprintf(buf, sizeof(buf), "\n================ LEAK DETECTOR REPORT ================\n");
write(STDERR_FILENO, buf, len);
pthread_mutex_lock(&list_mutex);
alloc_info_t *curr = head;
int leak_count = 0;
size_t total_bytes = 0;
while (curr != NULL) {
leak_count++;
total_bytes += curr->size;
len = snprintf(buf, sizeof(buf), "\nLeak: %p (%zu bytes)\n", curr->user_ptr, curr->size);
write(STDERR_FILENO, buf, len);
// Print backtrace
// We use backtrace_symbols_fd because it is async-signal-safe and simple
// It writes directly to the fd.
backtrace_symbols_fd(curr->backtrace, curr->backtrace_size, STDERR_FILENO);
// Clean up the list as we go
alloc_info_t *next = curr->next;
real_free(curr);
curr = next;
}
head = NULL;
pthread_mutex_unlock(&list_mutex);
if (leak_count == 0) {
len = snprintf(buf, sizeof(buf), "No leaks detected. Clean exit.\n");
write(STDERR_FILENO, buf, len);
} else {
len = snprintf(buf, sizeof(buf), "\nTOTAL LEAKS: %d allocations, %zu bytes\n", leak_count, total_bytes);
write(STDERR_FILENO, buf, len);
}
len = snprintf(buf, sizeof(buf), "======================================================\n");
write(STDERR_FILENO, buf, len);
}
// ============================================================================
// Hooked Functions
// ============================================================================
void *malloc(size_t size) {
// 1. Handle initialization bootstrap
if (!is_initialized) {
if (!in_hook) {
init_hooks();
}
// If dlsym triggers a malloc (it usually triggers calloc),
// or if we are still initializing, fallback to static buffer.
// This is a rough heuristic for the specific calloc case.
if (!is_initialized) {
void *ptr = bootstrap_buffer + bootstrap_offset;
bootstrap_offset += size + (16 - (size % 16)); // align
return ptr;
}
}
// 2. Call real malloc
void *ptr = real_malloc(size);
if (!ptr) return NULL;
// 3. Track it
// Note: To be 100% accurate, we should track BEFORE returning,
// but since we don't wrap the pointer (which slows down execution),
// we just log the returned pointer.
add_allocation(ptr, size);
return ptr;
}
void free(void *ptr) {
if (!ptr) return;
// Check if pointer is within our bootstrap buffer range (rough check)
if ((char*)ptr >= bootstrap_buffer && (char*)ptr < bootstrap_buffer + sizeof(bootstrap_buffer)) {
return; // Ignore frees for static bootstrap memory
}
// Initialize if not already (e.g., free called before malloc)
if (!is_initialized) init_hooks();
// 1. Untrack it
remove_allocation(ptr);
// 2. Call real free
real_free(ptr);
}
void *calloc(size_t nmemb, size_t size) {
// 1. Handle initialization (dlsym calls calloc!)
if (!is_initialized) {
if (!in_hook) {
init_hooks();
}
// Fallback for the specific calloc call inside dlsym
if (!is_initialized) {
size_t total = nmemb * size;
void *ptr = bootstrap_buffer + bootstrap_offset;
bootstrap_offset += total + (16 - (total % 16));
memset(ptr, 0, total); // calloc returns zeroed memory
return ptr;
}
}
// 2. Call real calloc
void *ptr = real_calloc(nmemb, size);
if (!ptr) return NULL;
// 3. Track it
add_allocation(ptr, nmemb * size);
return ptr;
}
void *realloc(void *ptr, size_t size) {
if (!is_initialized) init_hooks();
// 1. If ptr is NULL, behave like malloc
if (ptr == NULL) {
return malloc(size);
}
// 2. If size is 0, behave like free
if (size == 0) {
free(ptr);
return NULL;
}
// 3. Standard realloc logic
// Remove old tracking info first
remove_allocation(ptr);
// Reallocate
void *new_ptr = real_realloc(ptr, size);
if (new_ptr) {
// Add new tracking info
add_allocation(new_ptr, size);
} else {
// If realloc failed, the old memory is still valid.
// We should ideally re-add the old info, but for a simple detector
// we assume the program will likely abort or handle OOM.
// To be safe, we could re-add it, but the pointer might have changed
// semantics in the eyes of the tracker. Let's keep it simple.
}
return new_ptr;
}
2. Compilation
Compile the code into a shared object library. You must compile with -rdynamic to ensure symbols are exported for backtracing, and -ldl for dlsym.
gcc -shared -fPIC -o leak_detector.so leak_detector.c -ldl -rdynamic
3. Usage
Run your application with LD_PRELOAD pointing to the library.
LD_PRELOAD=./leak_detector.so ./your_application
Example Test
Create a dummy program test.c:
#include <stdlib.h>
#include <stdio.h>
void function_that_leaks() {
char *leak = malloc(100);
printf("Allocated 100 bytes at %p\n", leak);
// Ooops, forgot to free(leak)
}
int main() {
function_that_leaks();
char *no_leak = malloc(50);
free(no_leak);
return 0;
}
Compile and run:
gcc -o test test.c
LD_PRELOAD=./leak_detector.so ./test
4. Implementation Details & Gotchas
- The
calloc Bootstrap Problem: The function dlsym (used to find the real malloc) internally calls calloc. If our hooked calloc calls dlsym, we enter infinite recursion.
- Solution: We use a static buffer (
bootstrap_buffer) to serve memory requests during the initialization phase (dlsym calls).
- Thread Safety:
malloc can be called from multiple threads. We use pthread_mutex_lock to protect the linked list of allocations.
- Performance: This implementation creates a metadata node for every allocation using a real
malloc call internally. This effectively doubles the number of allocations your program makes and adds a mutex lock overhead. It works fine for debugging but will significantly slow down high-performance applications.
- Pointer Management: Unlike some more complex detectors that prefix the returned memory with a header (changing the pointer address), this implementation maps the exact pointer the user sees to the metadata via a linked list. This is less invasive but slightly slower on
free (O(N) lookup). For a debugging tool, this is usually acceptable.
- Realloc: Handling
realloc is tricky. If it moves memory, the old pointer is invalid. We handle this by removing the old tracking entry and adding a new one for the new pointer.