Custom Memory Debugger in C: Technical Breakdown
This post breaks down a lightweight, portable memory debugging system that tracks allocations, detects leaks, and catches double-free errors.
Core Architecture
The system revolves around a linked list that tracks every memory allocation with metadata about where it was allocated and whether it's been freed.
The Memory Header Structure
typedef struct MemHeader
{
size_t size; // Size of allocated memory
const char *file; // Source file name
int line; // Line number
int freed; // Flag: 0 = active, 1 = freed
struct MemHeader *next; // Linked list pointer
} MemHeader;
This header is prepended to every allocation, creating a "fat pointer" system where metadata travels with the allocated memory.
Global Tracking List
static MemHeader *alloc_head = NULL;
A single global pointer maintains the head of a singly-linked list containing all allocation records. This approach is simple but means the system isn't thread-safe without additional synchronization.
Technical Deep Dive
Memory Layout Strategy
The malloc_dbg function uses a clever memory layout technique:
MemHeader *newNode = malloc(sizeof(MemHeader) + size);
return (void *)(newNode + 1);
What happens here:
- Allocates space for both the header AND the requested memory in one block
- Places the
MemHeaderat the beginning of the allocation - Returns a pointer to the byte immediately after the header
Memory Layout:
[MemHeader][User Data...........]
^ ^
newNode returned pointer
This ensures the metadata is always accessible by subtracting one MemHeader size from any valid pointer.
Pointer Arithmetic in free_dbg
The free function reverses the pointer arithmetic:
MemHeader *header = ((MemHeader *)freeable) - 1;
This moves the pointer backward by exactly sizeof(MemHeader) bytes to access the metadata. This works because pointer arithmetic on typed pointers automatically scales by the type size.
Linked List Management
The allocation tracking uses a simple append-only linked list:
if (alloc_head == NULL) {
alloc_head = newNode;
} else {
MemHeader *alloc_head2 = alloc_head;
while (alloc_head2->next) {
alloc_head2 = alloc_head2->next;
}
alloc_head2->next = newNode;
}
Time Complexity: O(n) for each allocation due to the traversal to find the tail. This could be optimized with a tail pointer.
Double-Free Detection
The system detects double-free attempts by checking the freed flag:
if (header->freed) {
fprintf(stderr, "Free detected at %s:%d", header->file, header->line);
return;
}
header->freed = 1;
Important: The header isn't removed from the linked list when freed, just marked. This allows detection of subsequent free attempts on the same pointer.
Leak Detection Algorithm
void leaks_dbg() {
MemHeader *placeholder = alloc_head;
while (placeholder) {
if (!placeholder->freed) {
printf("\nMemory Leak of %zu bytes at %s:%d\n",
placeholder->size, placeholder->file, placeholder->line);
}
placeholder = placeholder->next;
}
}
Traverses the entire allocation list and reports any entries where freed is still 0.
Macro Magic for Automatic Location Tracking
#define malloc_dbg_wrapper(size) malloc_dbg(size, __FILE__, __LINE__)
#define free_dbg_wrapper(ptr) free_dbg(ptr)
The __FILE__ and __LINE__ preprocessor macros automatically inject the source location, making leak reports precise without manual annotation.
Technical Limitations & Considerations
Memory Overhead
- Per allocation:
sizeof(MemHeader)bytes (typically 32-40 bytes on 64-bit systems) - Global: Linked list nodes persist until program termination
Performance Characteristics
- malloc_dbg: O(n) where n = number of active allocations
- free_dbg: O(1)
- leaks_dbg: O(n) where n = total allocations ever made
Thread Safety
The current implementation is not thread-safe. Multiple threads could corrupt the linked list. Adding mutex protection around list operations would be necessary for multi-threaded applications.
Memory Alignment
The system maintains natural alignment since MemHeader is returned to the system allocator, and the user data starts at (MemHeader + 1), which should be properly aligned for most types.
Real-World Applications
Unit Testing Frameworks
Integrate into test suites to automatically detect memory leaks during test runs. Unlike Valgrind, this works in any environment and can be left enabled in CI/CD pipelines.
Embedded Systems Development
Critical for firmware where external debugging tools aren't available. The system provides memory leak detection on actual hardware without requiring special build configurations or external dependencies.
Game Development & Real-Time Systems
Memory leaks in games cause performance degradation over time. This system can be enabled during development builds to catch subsystem-specific leaks (audio, graphics, etc) with minimal performance impact.
Security-Critical Applications
Double-free vulnerabilities are a common attack vector. The built-in double-free detection helps identify potential security issues during development of network services, parsers, and other security-sensitive code.
Legacy Code Maintenance
When working with large, unfamiliar codebases, this system can be dropped in to quickly identify memory management issues without requiring deep code analysis or external tool setup.
Conclusion
This memory debugging system demonstrates how a small amount of carefully crafted C code can provide powerful debugging capabilities. The key insights are:
- Metadata co-location: Storing tracking information adjacent to user data
- Pointer arithmetic: Leveraging C's pointer arithmetic for efficient metadata access
- Persistent tracking: Keeping freed allocations in the list enables double-free detection
- Macro automation: Using preprocessor macros for seamless source location tracking
While not as comprehensive as dedicated tools like Valgrind, this approach provides a portable, lightweight alternative that can be invaluable in constrained environments or when you need debugging capabilities built directly into your application.
Comments
Post a Comment