Posts

Showing posts from July, 2025

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

Building a Dynamic Array in C: A Deep Dive into Memory Management

Dynamic arrays are one of the most fundamental data structures in programming, yet they're not built into C like they are in higher-level languages. Today, we'll explore how to implement a dynamic array from scratch in C, understanding the underlying memory management principles that make it work. What is a Dynamic Array? A dynamic array is a data structure that can grow or shrink in size during runtime, unlike static arrays whose size must be determined at compile time. This flexibility makes them incredibly useful for situations where you don't know how much data you'll need to store beforehand. The Structure Foundation Our implementation starts with a simple but powerful structure: #define initialCap 2 typedef struct {     int * data ;     int size ;     int capacity ; } DynamicArray ; This structure contains three crucial components: data : A pointer to the actual array elements stored in heap memory size : The current number of elements ...