Internal vs External fragmentation
What you'll learn: You will learn to distinguish between wasted space inside an allocated block and wasted space between blocks in your memory pool.
The Suitcase Analogy
Imagine you are packing for a trip.
Internal fragmentation is like buying a large suitcase to carry a single pair of socks. You’ve reserved the entire volume of that suitcase, but most of it is empty air. No one else can use that empty space because it is "inside" your reserved bag.
External fragmentation is like having ten small gaps under your bed. Totaled up, there is enough room for a giant suitcase, but because the space is broken into tiny, non-contiguous pieces, you can't actually fit the suitcase anywhere.
Internal Fragmentation: The Fixed-Size Problem
In custom allocators, we often round up a user's request to the nearest "power of two" or a specific word alignment (like 8 or 16 bytes) to keep the CPU happy.
If a user asks for 5 bytes, but your allocator only hands out 16-byte chunks, you have 11 bytes of internal fragmentation. That memory is allocated, but useless.
// Example of internal fragmentation
size_t requested = 5;
size_t actual_allocated = 16; // Rounded up for alignment
// 11 bytes are trapped inside this block
void* ptr = my_malloc(requested);
External Fragmentation: The Swiss Cheese Problem
This happens when you allocate and free blocks of different sizes over time. Your memory becomes a "Swiss cheese" of small holes.
Even if your total free memory is 100 KB, you might not be able to fulfill a 50 KB request if the free space is scattered in 1 KB fragments across the heap. The memory is there, but it isn't contiguous (touching).
// Example of external fragmentation
void* a = my_malloc(100); // [AAA]
void* b = my_malloc(100); // [AAA][BBB]
void* c = my_malloc(100); // [AAA][BBB][CCC]
my_free(a);
my_free(c);
// Memory looks like: [FREE][BBB][FREE]
// We have 200 bytes free, but we cannot allocate
// a single 150-byte block because the space is split.
void* d = my_malloc(150); // Fails!
Key takeaway
Internal fragmentation is wasted space inside a block due to rounding; external fragmentation is wasted space between blocks that is too small to be reused.