Course contentsShow
← C
Lesson 579 of 1,2198. Memory ManagementFree lesson

Building a simple free list

Building a simple free list

What you'll learn: How to track available memory blocks by chaining them together into a linked list.

The problem with "dead" memory

When you build a custom memory allocator, you typically start with a large chunk of memory (a buffer). When a user "frees" a piece of that memory, you can't just let it vanish. You need a way to remember where that empty space is so you can hand it out again later. If you don't track it, you'll eventually run out of fresh space, even if most of your buffer is technically empty.

The "Breadcrumb" approach

Think of a free list like a scavenger hunt. Instead of keeping a separate, complex map of every empty hole in your memory, you store the "map" inside the holes themselves.

When a block of memory is not being used by the program, we treat the start of that block as a small structure (a "node") that holds a pointer to the next available block. We only need one global variable—the head—to point to the first piece of free memory. Each free block then points to the next, forming a chain.

Implementation in C

To do this, we define a simple structure. Even if a free block is 100 bytes large, we only need the first few bytes to store our Node.

#include <stddef.h>

// This represents a hole in our memory
struct FreeNode {
    struct FreeNode* next;
};

// The starting point of our chain
struct FreeNode* free_list_head = NULL;

void add_to_free_list(void* ptr) {
    // Treat the newly freed memory as a FreeNode
    struct FreeNode* node = (struct FreeNode*)ptr;
    
    // Insert it at the beginning of the list (Push)
    node->next = free_list_head;
    free_list_head = node;
}

void* get_from_free_list() {
    if (free_list_head == NULL) return NULL;

    // Pop the first available block off the list
    struct FreeNode* allocated_node = free_list_head;
    free_list_head = free_list_head->next;
    
    return (void*)allocated_node;
}

Why this is efficient

This technique is powerful because it requires zero extra memory beyond a single head pointer. We are reusing the "dead" space to store the navigation links. When the user needs memory, we "pop" the head off the list. When they return it, we "push" it back onto the list.

Key takeaway

A free list turns unused memory blocks into a linked list by storing pointers inside the empty spaces themselves.