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 withou...