Conceptualizing a Detector
I'm currently focused on the detector's core functionality. I've begun to break down the requirements. The language is C, for Linux user-space applications. I'm prioritizing the essential features, such as how to track memory allocations and deallocations. Considering how to integrate into existing programs without causing significant overhead is a major consideration.
Prioritizing the Implementation
Now, I'm leaning heavily towards the LD_PRELOAD approach. The function hooking will intercept malloc, calloc, realloc, and free. I need a way to track the allocated memory blocks. A linked list seems sensible to maintain a record of the allocated pointers and sizes, which will be checked at program exit. I need to consider thread safety.
Considering Refinement of Approach
I'm now deep-diving into the LD_PRELOAD method. Thinking about thread safety, I've decided to use a mutex for the linked list operations. Regarding metadata, I'm now figuring out the best ways to get the file and line number where the allocation happens. This turns out to be tricky; I'm weighing options such as utilizing a compiler flag to inject this information or doing stack walking. The compiler flag approach looks to be far simpler. I'll need to figure out how to pass this info to the overloaded malloc function.
Refining Implementation Strategy
I'm now refining the LD_PRELOAD strategy based on the analysis. I've ruled out using a hash table because of the increased complexity. I've also decided not to track the file/line numbers initially, but will add it later using compile-time instrumentation. To prevent recursive calls, I'm thinking of using a static buffer and function pointers initialized on library load. For demonstration simplicity, the macro wrapper method seems a better way to go.
Choosing the Best Path Forward
My thoughts have taken a turn, shifting focus. I'm now certain that a hybrid approach is optimal. I'll begin by detailing the macro-wrapper method. It will highlight file/line information, which is central for effective debugging. Simultaneously, I plan to discuss the LD_PRELOAD method, as requested in the prompt. This will provide a more comprehensive and well-rounded perspective, ensuring the end-user gains full insight.
Revising Implementation Strategy
I've re-evaluated my course. I'll now focus on the macro wrapper for source code instrumentation. I'll outline its benefits like file/line number reporting, then describe the LD_PRELOAD alternative. This method simplifies debugging by directly connecting allocations with their origin. It provides a more comprehensive viewpoint for the end user and will ensure a strong base to work from.
Defining Implementation Details
Now, I'm fully committed to delivering the macro-wrapper approach. It offers a direct connection between allocations and their source code locations. For completeness, I'll detail the LD_PRELOAD alternative. This ensures the user has a comprehensive view, allowing them to choose the method that best suits their needs, enhancing flexibility and understanding.
Defining the Implementation
The core implementation is now cemented: a macro wrapper. This strategy directly links allocations to their source location, which is a great starting point for debugging. The secondary implementation, LD_PRELOAD, will also be detailed, providing a comprehensive user experience by contrasting the techniques and highlighting their benefits. I'm confident in this path.
Defining the Core Strategy
My thinking has solidified. The focus will be on the macro wrapper approach, highlighting file and line numbers for precise debugging. However, I will also detail the LD_PRELOAD method, giving a comprehensive view, offering options for diverse use cases. This provides an excellent learning path, emphasizing practical applicability.
Here is a robust implementation of a memory leak detector in C using the Source Instrumentation (Macro Wrapper) technique.
This is generally preferred over LD_PRELOAD hooks for development because it captures __FILE__ and __LINE__, telling you exactly where in your code the leak occurred.
The Architecture
- Header File (
leak_detector.h): Redefines malloc, calloc, realloc, and free using preprocessor macros to pass file and line number information.
- Implementation (
leak_detector.c): Maintains a thread-safe doubly linked list of all active allocations.
- Cleanup: Registers an
atexit handler to automatically print the leak report when the program terminates.
1. The Header (leak_detector.h)
Include this header in any C file where you want to track leaks.
#ifndef LEAK_DETECTOR_H
#define LEAK_DETECTOR_H
#include <stddef.h>
// Function prototypes for our internal wrappers
void* leak_malloc(size_t size, const char* file, unsigned int line);
void* leak_calloc(size_t num, size_t size, const char* file, unsigned int line);
void* leak_realloc(void* ptr, size_t size, const char* file, unsigned int line);
void leak_free(void* ptr);
// Initialize the detector (optional, but good for explicit setup)
void leak_detector_init(void);
// Macros to intercept standard calls
// We utilize the preprocessor to swap standard calls with our tracked versions
#define malloc(size) leak_malloc(size, __FILE__, __LINE__)
#define calloc(num, size) leak_calloc(num, size, __FILE__, __LINE__)
#define realloc(ptr, size) leak_realloc(ptr, size, __FILE__, __LINE__)
#define free(ptr) leak_free(ptr)
#endif
2. The Implementation (leak_detector.c)
This file handles the metadata tracking.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
// Important: Undefine the macros so we can use the REAL system calls internally
#undef malloc
#undef calloc
#undef realloc
#undef free
// Structure to track allocation info
typedef struct _mem_info {
void *address;
size_t size;
const char *file;
unsigned int line;
struct _mem_info *next;
struct _mem_info *prev;
} mem_info;
// Head of our linked list
static mem_info *head = NULL;
// Mutex to ensure thread safety
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
// Helper: Add allocation to list
static void add_mem_info(void *ptr, size_t size, const char *file, unsigned int line) {
pthread_mutex_lock(&lock);
mem_info *info = (mem_info*)malloc(sizeof(mem_info));
if (!info) {
fprintf(stderr, "Leak Detector Error: Could not allocate memory for metadata.\n");
pthread_mutex_unlock(&lock);
return;
}
info->address = ptr;
info->size = size;
info->file = file;
info->line = line;
info->next = head;
info->prev = NULL;
if (head) {
head->prev = info;
}
head = info;
pthread_mutex_unlock(&lock);
}
// Helper: Remove allocation from list
static void remove_mem_info(void *ptr) {
pthread_mutex_lock(&lock);
mem_info *current = head;
while (current) {
if (current->address == ptr) {
if (current->prev) {
current->prev->next = current->next;
} else {
head = current->next;
}
if (current->next) {
current->next->prev = current->prev;
}
free(current);
pthread_mutex_unlock(&lock);
return;
}
current = current->next;
}
// If we reach here, the user tried to free an invalid pointer or double-free
// fprintf(stderr, "Double free or invalid free detected at %p\n", ptr);
pthread_mutex_unlock(&lock);
}
// Wrapper functions
void* leak_malloc(size_t size, const char* file, unsigned int line) {
void *ptr = malloc(size);
if (ptr) {
add_mem_info(ptr, size, file, line);
}
return ptr;
}
void* leak_calloc(size_t num, size_t size, const char* file, unsigned int line) {
void *ptr = calloc(num, size);
if (ptr) {
add_mem_info(ptr, num * size, file, line);
}
return ptr;
}
void* leak_realloc(void* ptr, size_t size, const char* file, unsigned int line) {
// If ptr is NULL, realloc acts like malloc
if (!ptr) {
return leak_malloc(size, file, line);
}
// If size is 0, acts like free
if (size == 0) {
leak_free(ptr);
return NULL;
}
// We must remove the old entry and add the new one because the address might change
remove_mem_info(ptr);
void *new_ptr = realloc(ptr, size);
if (new_ptr) {
add_mem_info(new_ptr, size, file, line);
}
return new_ptr;
}
void leak_free(void* ptr) {
if (ptr) {
remove_mem_info(ptr);
free(ptr);
}
}
// Reporting function called at program exit
void report_leaks(void) {
pthread_mutex_lock(&lock);
mem_info *current = head;
size_t total_leak = 0;
int leak_count = 0;
if (current == NULL) {
printf("\n-----------------------------------\n");
printf(" Memory Leak Check: NO LEAKS \n");
printf("-----------------------------------\n");
} else {
printf("\n-----------------------------------\n");
printf(" Memory Leak Check: LEAKS DETECTED \n");
printf("-----------------------------------\n");
printf("%-20s %-10s %-10s\n", "File", "Line", "Size");
printf("-----------------------------------\n");
while (current) {
printf("%-20s %-10d %-10zu bytes\n",
current->file, current->line, current->size);
total_leak += current->size;
leak_count++;
// Move to next and clean up the metadata node itself (since program is ending)
mem_info *temp = current;
current = current->next;
free(temp);
}
printf("-----------------------------------\n");
printf("Total Leaks: %d\n", leak_count);
printf("Total Bytes: %zu\n", total_leak);
printf("-----------------------------------\n");
}
pthread_mutex_unlock(&lock);
}
// Initializer to register the report function
void leak_detector_init(void) {
static int initialized = 0;
if (!initialized) {
atexit(report_leaks);
initialized = 1;
}
}
3. Usage Example (main.c)
#include <stdio.h>
#include <stdlib.h> // Must be included BEFORE leak_detector.h if using system basics
#include "leak_detector.h"
void create_leak() {
// Leak 1
int *ptr = (int*)malloc(sizeof(int) * 10);
ptr[0] = 100;
// We forgot to free ptr!
}
int main() {
// Initialize the report handler
leak_detector_init();
printf("Program starting...\n");
// Valid Allocation
void *p1 = malloc(100);
free(p1);
// Leak 2
char *s = (char*)calloc(50, sizeof(char));
// Oops, forgot to free s!
create_leak();
printf("Program finished. Checking for leaks...\n");
return 0;
}
4. How to Build and Run
You need to compile the source files together and link the pthread library.
gcc -o leak_test main.c leak_detector.c -lpthread
./leak_test
5. Expected Output
Program starting...
Program finished. Checking for leaks...
-----------------------------------
Memory Leak Check: LEAKS DETECTED
-----------------------------------
File Line Size
-----------------------------------
main.c 23 50 bytes
main.c 7 40 bytes
-----------------------------------
Total Leaks: 2
Total Bytes: 90
-----------------------------------
Key Implementation Details
- Recursion Prevention: In
leak_detector.c, we #undef malloc/free at the top. This ensures that when our wrapper calls malloc, it calls the libc version, not our wrapper recursively (which would cause a stack overflow).
- Thread Safety: A global
pthread_mutex_t protects the linked list. If you are debugging a multi-threaded application, multiple threads allocating memory simultaneously won't corrupt the detector's metadata.
- Allocation Metadata: We use a doubly linked list. While O(N) insertion/deletion is slower than a hash map, it is sufficient for debugging purposes and significantly easier to implement in C without external libraries.
atexit: By using atexit(report_leaks), the report prints automatically when main returns, even if you have multiple exit points.
Limitations
- Libraries: This method only detects leaks in code that you compile with
#include "leak_detector.h". It will not detect leaks inside pre-compiled 3rd-party libraries. (For that, you would use a tool like Valgrind).
- Performance: It adds overhead to every allocation (locking mutex, allocating metadata node). It is intended for Debug builds, not Production Release builds.