The user is asking for help with implementing a memory leak detector in C for Linux applications. They likely want guidance and some coding examples, focusing on using a simple allocator wrapper that can track memory allocations and detect leaks at program exit. I’m considering approaches like using LD_PRELOAD to interpose malloc/free or utilizing macros/debug allocators. Valgrind and ASan could also be options, but since the user specifically wants an implementation, I need to focus on providing actual C code. I plan to present two design options: a compile-time instrumented library and an LD_PRELOAD interposer, but we can choose one for clarity.Implementing a Memory Tracker
I’m considering a memory tracker that uses macros to wrap malloc/free/calloc/realloc. It would maintain a hash table or balanced tree of allocations, keyed by pointer while storing size, file, and line number for each entry. This way, I can print any still-allocated blocks at exit using an atexit handler. The tracker will be a static source file that the user includes. I'll need to ensure thread safety with pthread_mutex, but I must watch for possible recursion issues if malloc is called within the tracker. A simpler static array could be used, but it would limit the maximum number of allocations.Improving Memory Allocation Tracking
I’m exploring the idea of implementing a small allocator using brk/sbrk or mmap for the tracking metadata. Alternatively, I could rely on glibc but use a "reentry guard" with a thread-local storage variable to skip tracking during internal malloc calls to avoid recursion issues. A simpler option is to use static __thread int inside, which would allow the real malloc/free to execute without tracking when the inside variable is greater than zero.
I need to ensure that the my_malloc macro expands correctly to call dbg_malloc(size, file, line) and handle the implementation where the macro can control when to use the original libc malloc by undefining it in the implementation file.Designing a Memory Leak Detector
I’m drafting a header file for a memory leak detector, named memory_leak_detector.h. It will include functions to initialize the detector, dump leaks, and various memory allocation functions such as mld_malloc, mld_calloc, mld_realloc, and mld_free. I'll define a macro to wrap the standard malloc to include file and line information.
In the implementation file memory_leak_detector.c, I'll use a hash table with separate chaining to track allocations, utilizing simple hashing. I'll set up a structure to hold allocation information, ensuring to manage mutex for thread safety. To avoid recursion issues when calling malloc, I'll ensure macros are defined only in the header, allowing raw libc allocations within the implementation.Finalizing Memory Leak Detector Implementation
I need to ensure that my code handles macro definitions properly, only including them when MLD_DISABLE is not defined. In the library implementation, I’ll define MLD_INTERNAL to disable macros, allowing direct access to raw libc allocations. I'll also manage bookkeeping correctly, freeing memory in mld_free and addressing edge cases like double frees.
For mld_realloc, I'll handle cases where the pointer is NULL or the size is zero while ensuring proper tracking of allocations. I must be cautious with threading and use pthread_once for initialization. The use of __attribute__((constructor)) can be handy for automatic handler registration.
The hash table design will be straightforward, using a simple unsigned long hash function. I’ll implement functions to register allocations, manage locks during operations, and carefully update records in realloc scenarios.
In my final design, I’ll provide code listings and compilation instructions, and I'll mention the alternative of using LD_PRELOAD for more advanced users, ensuring compatibility with standard C for Linux applications using glibc. I believe this will yield a minimal but effective memory leak detection solution.Designing Memory Leak Detector
I need to handle special cases for the realloc function and manage memory correctly. If the size is zero, I'll treat it as a mld_free call. In the mld_free function, I must ensure to remove the allocation record safely while locking the mutex to prevent concurrent modifications.
When dealing with logging and memory leaks, I'll ensure no user macros affect these calls. We can track allocations in a simple hash table, and I’ll carefully implement the remove functions while logging attempts to free untracked pointers.
Additionally, I should provide a clean solution for linking detection via LD_PRELOAD, but I think the primary emphasis will be on a simple, robust, compile-time leak detection approach. This will involve crafting concise documentation, showing how to use the header, and compiling examples while keeping verbosity manageable.Implementing Memory Leak Detector
I'm looking to avoid macro redefinition when using system headers. To prevent conflicts, the user should include our custom header mld.h last. In mld.c, I’ll set up necessary includes and a static hash table for allocations, making sure to implement mld_dump_leaks for manual inspection and automatic calls using atexit.
I’ll ensure that the destructor runs smoothly in multi-threaded environments, but I think I prefer asking the user to call mld_init. By using a mutex, I can handle concurrency issues, keeping the implementation straightforward but effective. Then it's time to document everything clearly, highlighting limitations.Implementing Memory Management Functions
I'm developing a memory leak detector, starting with the mld_dump_leaks function that will gather and report outstanding allocations. I need to be cautious, ensuring I don't access freed memory at exit.
In mld_free, I’ll check for untracked pointers and handle them accordingly. The same applies to mld_malloc, mld_calloc, and mld_realloc, making sure that reallocations preserve necessary metadata.
There are some nuances, especially around realloc failures and how to retain accurate allocation info. Using mutexes will help manage concurrency effectively, and I’ll keep the implementation clean and documented without excessive verbosity.Implementing the Leak Detector
I'm working on the mld_dump_leaks function to report memory leaks. It will lock a mutex, iterate through the allocation table, printing leaks found while keeping a total count. If there are no leaks, it will report that as well.
I need to ensure that users don't call mld_malloc directly and remind them to include mld.h after standard headers.
I'll also provide compilation instructions and mention using LD_PRELOAD for dynamic linking while clarifying its limitations compared to tools like Valgrind. Now, it's all about crafting a concise final answer with code examples and disclaimers! Below is a complete, minimal memory-leak detector you can integrate into C programs on Linux. It works by:
Wrapping malloc, calloc, realloc, free via macros.
Tracking every allocation (pointer, size, file, line) in a hash table.
Reporting any allocations that were never freed at program exit.
This requires recompiling the target program, but no changes to its code beyond including one header.
1. Public header: mld.h
Include this after standard headers (e.g. after <stdlib.h>), so the macros override the usual functions in your source files.
c
/* mld.h - simple memory leak detector
*
* Usage:
* #include <stdlib.h>
* #include "mld.h" // include AFTER system headers
*
* int main(void) {
* char *p = malloc(100);
* // forget to free(p);
* return 0;
* }
*
* At program exit, leaks are printed to stderr.
*/
#ifndef MLD_H
#define MLD_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
void *mld_malloc(size_t size, const char *file, int line);
void *mld_calloc(size_t nmemb, size_t size, const char *file, int line);
void *mld_realloc(void *ptr, size_t size, const char *file, int line);
void mld_free(void *ptr, const char *file, int line);
/* Manually dump current leaks (also called automatically at exit). */
void mld_dump_leaks(void);
#ifdef __cplusplus
}
#endif
/* Do not remap inside the implementation itself. */
#ifndef MLD_INTERNAL
# define malloc(sz) mld_malloc((sz), __FILE__, __LINE__)
# define calloc(n,sz) mld_calloc((n), (sz), __FILE__, __LINE__)
# define realloc(p,sz) mld_realloc((p), (sz), __FILE__, __LINE__)
# define free(p) mld_free((p), __FILE__, __LINE__)
#endif
#endif /* MLD_H */
#include <stdio.h>
#include <stdlib.h>
#include "mld.h" /* include after stdlib.h */
int main(void)
{
char *p = malloc(100);
char *q = malloc(50);
free(q);
/* forget to free p */
return 0;
}
Run:
bash
./myprog
Example output to stderr:
code
MLD: leak: 100 bytes at 0x55dbb4c6b2a0 allocated at myprog.c:8
MLD: SUMMARY: 100 bytes leaked in 1 blocks
If you double-free or free pointers that were never allocated (or not through these wrappers), you get diagnostics like:
code
MLD: free of untracked pointer 0x55dbb4c6b2a0 at myprog.c:10
4. Notes and possible extensions
This only tracks allocations done via the wrapped malloc/calloc/realloc in code that includes mld.h. Library code that calls malloc directly (without going through your macros) will not be tracked.
For tracking arbitrary binaries without recompilation, you can instead:
Build a shared object that defines real malloc, calloc, realloc, free and uses dlsym(RTLD_NEXT, ...) to call the original implementations.
Use LD_PRELOAD=./leakdetector.so your_program to interpose on allocations.
This detects unfreed allocations, not use-after-free or buffer overruns. For those, tools like AddressSanitizer or Valgrind are more appropriate.
If you’d like, I can also provide an LD_PRELOAD-based version that works without modifying the target program’s source.
#define _GNU_SOURCE
#define MLD_INTERNAL /* disable macros in this translation unit */
#include "mld.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <pthread.h>
/* Simple hash-table-based tracker */
typedef struct AllocInfo {
void *ptr;
size_t size;
const char *file;
int line;
struct AllocInfo *next;
} AllocInfo;
/* Must be a power of two if using '&' instead of '%' */
#define MLD_HASH_SIZE 4096
static AllocInfo *mld_table[MLD_HASH_SIZE];
static pthread_mutex_t mld_lock = PTHREAD_MUTEX_INITIALIZER;
static unsigned long mld_hash_ptr(void *ptr)
{
return ((uintptr_t)ptr >> 3) & (MLD_HASH_SIZE - 1);
}
static void mld_add_allocation(void *ptr, size_t size,
const char *file, int line)
{
if (!ptr)
return;
AllocInfo *info = (AllocInfo *)malloc(sizeof(AllocInfo));
if (!info) {
/* Out of memory for bookkeeping; give up tracking this one. */
return;
}
info->ptr = ptr;
info->size = size;
info->file = file;
info->line = line;
unsigned long h = mld_hash_ptr(ptr);
pthread_mutex_lock(&mld_lock);
info->next = mld_table[h];
mld_table[h] = info;
pthread_mutex_unlock(&mld_lock);
}
/* Remove allocation record for ptr and return it (caller frees the node). */
static AllocInfo *mld_remove_allocation(void *ptr)
{
unsigned long h = mld_hash_ptr(ptr);
pthread_mutex_lock(&mld_lock);
AllocInfo *prev = NULL;
AllocInfo *cur = mld_table[h];
while (cur) {
if (cur->ptr == ptr) {
if (prev)
prev->next = cur->next;
else
mld_table[h] = cur->next;
pthread_mutex_unlock(&mld_lock);
return cur;
}
prev = cur;
cur = cur->next;
}
pthread_mutex_unlock(&mld_lock);
return NULL; /* not found */
}
/* Public API implementations */
void *mld_malloc(size_t size, const char *file, int line)
{
void *ptr = malloc(size);
mld_add_allocation(ptr, size, file, line);
return ptr;
}
void *mld_calloc(size_t nmemb, size_t size, const char *file, int line)
{
void *ptr = calloc(nmemb, size);
/* This may overflow, but it's only for reporting. */
mld_add_allocation(ptr, nmemb * size, file, line);
return ptr;
}
void *mld_realloc(void *ptr, size_t size, const char *file, int line)
{
if (ptr == NULL) {
return mld_malloc(size, file, line);
}
if (size == 0) {
mld_free(ptr, file, line);
return NULL;
}
/* Remove any existing tracking for the old pointer. */
AllocInfo *info = mld_remove_allocation(ptr);
void *new_ptr = realloc(ptr, size);
if (!new_ptr) {
/* realloc failed; old block is still valid. Restore tracking. */
if (info) {
mld_add_allocation(ptr, info->size, info->file, info->line);
free(info);
}
return NULL;
}
/* Track the (possibly moved) new block as a fresh allocation. */
if (info)
free(info);
mld_add_allocation(new_ptr, size, file, line);
return new_ptr;
}
void mld_free(void *ptr, const char *file, int line)
{
if (!ptr)
return;
AllocInfo *info = mld_remove_allocation(ptr);
if (!info) {
/* Double free or freeing untracked pointer. */
fprintf(stderr,
"MLD: free of untracked pointer %p at %s:%d\n",
ptr, file, line);
} else {
free(info);
}
free(ptr);
}
/* Dump all currently outstanding allocations. */
void mld_dump_leaks(void)
{
pthread_mutex_lock(&mld_lock);
size_t total_bytes = 0;
size_t total_blocks = 0;
for (size_t i = 0; i < MLD_HASH_SIZE; ++i) {
for (AllocInfo *cur = mld_table[i]; cur; cur = cur->next) {
fprintf(stderr,
"MLD: leak: %zu bytes at %p allocated at %s:%d\n",
cur->size, cur->ptr, cur->file, cur->line);
total_bytes += cur->size;
total_blocks += 1;
}
}
if (total_blocks > 0) {
fprintf(stderr,
"MLD: SUMMARY: %zu bytes leaked in %zu blocks\n",
total_bytes, total_blocks);
} else {
fprintf(stderr, "MLD: no leaks detected\n");
}
pthread_mutex_unlock(&mld_lock);
}
/* Automatically dump leaks at process exit. */
__attribute__((constructor))
static void mld_constructor(void)
{
/* Ensure mld_dump_leaks is called when the program exits. */
atexit(mld_dump_leaks);
}