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

The concept of memory fragmentation

The concept of memory fragmentation

What you'll learn: How scattered gaps in memory can prevent you from allocating large blocks, even when you have enough total space available.

The Parking Lot Problem

Imagine a parking lot with ten empty spaces. If all ten spaces are side-by-side, you can easily park a long bus. But if ten small cars park in every other spot, you still have ten empty spaces, yet you can’t park the bus anywhere. The empty space is "fragmented."

In C, memory management suffers from this same issue. Even if your system has 100 MB of free RAM, you might fail to allocate a single 10 MB array if that free memory is broken into a thousand tiny, non-contiguous holes.

External vs. Internal Fragmentation

There are two main ways memory gets messy:

  1. External Fragmentation: This happens when free memory is separated by blocks that are currently in use. As you malloc() and free() objects of different sizes over time, your heap starts to look like Swiss cheese. The total free space is high, but the largest contiguous block is small.
  2. Internal Fragmentation: This happens when you allocate more memory than you actually need. If your allocator only hands out memory in chunks of 1024 bytes, but you only asked for 10 bytes, the remaining 1014 bytes are "trapped" inside that allocation and cannot be used by anything else.

Why it matters for Custom Allocators

When you build your own allocator, you have to decide how to manage these gaps. If you simply grab the first hole you find, you might leave behind tiny slivers of memory that are too small to ever be used again.

#include <stdlib.h>
#include <stdio.h>

int main() {
    // Imagine we allocate four small objects
    void* a = malloc(100);
    void* b = malloc(100); // This sits between a and c
    void* c = malloc(100);
    void* d = malloc(100);

    // We free 'b' and 'd'
    free(b);
    free(d);

    // We now have 200 bytes free, but it is split into two 100-byte holes.
    // The following will fail if the allocator can't find 150 contiguous bytes:
    void* large_ptr = malloc(150); 
    
    if (large_ptr == NULL) {
        printf("Fragmentation prevented allocation!\n");
    }

    free(a);
    free(c);
    return 0;
}

Key takeaway

Fragmentation is the buildup of unusable gaps in memory that occurs when free space is not contiguous or when allocated blocks are larger than the data they hold.