Allocation strategies: First-fit
What you'll learn: How the First-fit strategy efficiently searches a free list to find the first available block of memory that meets a request's size requirements.
The Search for Space
When you build a custom memory allocator, you typically maintain a "free list"—a linked list of memory blocks that are currently not in use. When a user asks for 64 bytes of memory, your allocator has to decide which block from that list to hand over.
First-fit is the simplest and often fastest strategy for this search. As the name suggests, the allocator starts at the beginning of the free list and scans forward. The very first block it encounters that is large enough to hold the requested size is the winner.
The Parking Lot Analogy
Imagine you are driving a car into a long, linear parking lot. You are tired and just want to get out of the car. In a First-fit mindset, you don't care if there is a "perfect" spot further down that fits your compact car exactly. You take the very first spot you see that is wide enough for your vehicle, even if it’s a giant spot meant for a truck.
This saves you time driving around (CPU cycles), even if it isn't the most "organized" way to fill the lot.
How it looks in code
In a First-fit system, your allocation function loops through the blocks and returns as soon as it finds a match.
typedef struct Block {
size_t size;
int free;
struct Block* next;
} Block;
Block* find_first_fit(Block* head, size_t requested_size) {
Block* current = head;
while (current != NULL) {
// If the block is free and big enough, grab it immediately!
if (current->free && current->size >= requested_size) {
return current;
}
current = current->next;
}
return NULL; // No suitable block found
}
Why use First-fit?
The primary advantage of First-fit is speed. Because it doesn't need to look at every single block in the list (unlike "Best-fit," which searches the whole list to find the smallest possible match), it spends less time traversing memory.
However, the downside is "fragmentation." First-fit tends to clutter the beginning of your memory pool with small, leftover fragments of blocks, forcing the allocator to skip over many tiny, useless holes to find large spaces at the end of the list later on.
Key takeaway
First-fit allocates the first available block that is large enough, prioritizing search speed over perfect space efficiency.