Memory allocation: first-fit, best-fit, worst-fit
Where does malloc find space? First-fit, best-fit and worst-fit, fragmentation, and both KTU allocation questions solved.
Syllabus says: “Memory allocation - First-fit, Best-fit, and Worst-fit allocation schemes”
On this page · 13 sections
FIRST = first hole that fits (fastest). BEST = smallest hole that fits (tightest). WORST = biggest hole (leaves the biggest leftover).
Parking a car: first-fit takes the first slot you see that is big enough; best-fit hunts for the snuggest slot; worst-fit parks in the biggest empty space so the remaining gap is still useful.
First-fit allocates the first free block large enough, best-fit the smallest free block large enough, and worst-fit the largest free block; leftover space stays on the free list.
ആദ്യം കിട്ടിയത് (first), ചേർന്നത് (best), വലുത് (worst).
What you will be able to do
- Explain the free list and how allocation and de-allocation work.
- Apply first-fit, best-fit and worst-fit to a request sequence (Nov 2025 Q12a, May 2026 Q12a).
- Distinguish internal and external fragmentation.
The story
The heap is a big slab of memory. Programs keep asking for pieces (malloc) and returning them (free). The memory manager keeps a free list of holes. For every request it must pick a hole — and the picking rule makes a big difference over time.
The three schemes
| Scheme | Rule | Speed | Side effect |
|---|---|---|---|
| First-fit | Scan from the start; take the first hole ≥ request | fast (stops early) | small leftovers pile up near the start |
| Best-fit | Take the smallest hole ≥ request | slow (scan all, unless sorted) | leaves tiny, often useless holes |
| Worst-fit | Take the largest hole | slow (scan all) | leftovers stay big; but big holes get used up |
After allocation, the unused part of the hole stays on the free list as a smaller hole. On free(), the block returns to the list and is merged (coalesced) with neighbouring free blocks so that holes do not keep shrinking.
External fragmentation: enough total free memory exists, but it is split into holes too small for the request. Internal fragmentation: an allocated block is bigger than requested (e.g. fixed partitions or rounding up), and the extra space inside it is wasted.
Worked example
Blocks: 150K, then 350K. Requests in order: 300K, 25K, 125K, 50K. Leftover space of a block stays usable.
| Request | First-fit | Best-fit | Worst-fit |
|---|---|---|---|
| 300K | 350K → left 50K | 350K → left 50K | 350K → left 50K |
| 25K | 150K → left 125K | 50K → left 25K (smallest fit) | 150K → left 125K (largest) |
| 125K | 125K → left 0 | 150K → left 25K | 125K → left 0 |
| 50K | 50K → left 0 ✓ | holes 25K, 25K → FAILS ✗ | 50K → left 0 ✓ |
Answer: first-fit and worst-fit satisfy all four requests. Best-fit cannot place the 50K request (only two 25K holes remain).
KTU May 2026 Q12a — solved
Partitions: 200K, 400K, 600K, 500K, 300K, 250K. Processes in order: 357K, 210K, 468K, 491K.
| Process | First-fit | Best-fit | Worst-fit |
|---|---|---|---|
| 357K | 400K (left 43K) | 400K (left 43K) | 600K (left 243K) |
| 210K | 600K (left 390K) | 250K (left 40K) | 500K (left 290K) |
| 468K | 500K (left 32K) | 500K (left 32K) | none ≥ 468K → waits ✗ |
| 491K | none ≥ 491K → waits ✗ | 600K (left 109K) ✓ | none → waits ✗ |
Answer: only best-fit places all four processes. The result is the same whether or not the leftover part of a partition can be reused, because no later process fits in any leftover.
Now watch it run
Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶. Keys: Space play/pause, ← → step.
C implementation
memory_allocation.ctested ✓ 720/720 cases/* First-fit, best-fit and worst-fit allocation — KTU PCCST303, Module 2
* (KTU Nov 2025 Q12a, May 2026 Q12a)
* Memory is a list of segments; each segment belongs to a block and is either a hole or
* holds one process. Requests are served in order; a request that fits nowhere waits.
* split mode : the leftover part of a hole stays a (smaller) hole — variable partitions
* fixed mode : the whole hole goes to the process, leftover is wasted — fixed partitions
* Input : n size1 ... sizen scheme F|B|W mode S|X then commands until EOF:
* A size (allocate; processes are named P1, P2, ... in request order)
* F k (free process Pk: coalesce with neighbouring holes, retry waiting ones)
* C (compact: move all processes to the start, one big hole at the end)
* Output: "P<k> -> <block index>" lines (0-based), "WAIT: P..", and the final segments. */
#include <stdio.h>
#include <string.h>
#define MAXS 64
struct seg { int block, size, owner, waste; }; /* owner 0 = hole */
struct seg m[MAXS];
int nseg, nblocks, blockSize[16];
char scheme, mode;
int waitPid[32], waitSize[32], nwait;
int placedBlock[33]; /* -1 = not in memory */
/* index of the hole chosen by the current scheme, or -1 */
int chooseHole(int r) {
int i, pick = -1;
for (i = 0; i < nseg; i++) {
if (m[i].owner != 0 || m[i].size < r) continue;
if (pick == -1) pick = i;
else if (scheme == 'B' && m[i].size < m[pick].size) pick = i; /* smallest that fits */
else if (scheme == 'W' && m[i].size > m[pick].size) pick = i; /* largest */
if (scheme == 'F') break; /* first that fits */
}
return pick;
}
void place(int pid, int r, int i) {
int left = m[i].size - r;
if (mode == 'S' && left > 0) { /* split: process part + new hole */
memmove(&m[i + 2], &m[i + 1], (size_t)(nseg - i - 1) * sizeof m[0]);
nseg++;
m[i + 1].block = m[i].block; m[i + 1].size = left; m[i + 1].owner = 0; m[i + 1].waste = 0;
m[i].size = r;
} else if (mode == 'X') { m[i].size = r; m[i].waste = left; } /* rest of the block is wasted */
m[i].owner = pid;
placedBlock[pid] = m[i].block;
}
void removeSeg(int i) { memmove(&m[i], &m[i + 1], (size_t)(nseg - i - 1) * sizeof m[0]); nseg--; }
void retryWaiting(int onlyFirstFitHole) {
int k, still = 0;
for (k = 0; k < nwait; k++) {
int i;
if (onlyFirstFitHole) { for (i = 0; i < nseg && !(m[i].owner == 0 && m[i].size >= waitSize[k]); i++) { } if (i == nseg) i = -1; }
else i = chooseHole(waitSize[k]);
if (i < 0) { waitPid[still] = waitPid[k]; waitSize[still] = waitSize[k]; still++; }
else place(waitPid[k], waitSize[k], i);
}
nwait = still;
}
void freeProcess(int pid) {
int i;
for (i = 0; i < nseg && m[i].owner != pid; i++) { }
if (i == nseg) { printf("P%d is not in memory\n", pid); return; }
m[i].owner = 0; m[i].size += m[i].waste; m[i].waste = 0;
placedBlock[pid] = -1;
if (i + 1 < nseg && m[i + 1].owner == 0 && m[i + 1].block == m[i].block) { m[i].size += m[i + 1].size; removeSeg(i + 1); }
if (i > 0 && m[i - 1].owner == 0 && m[i - 1].block == m[i].block) { m[i - 1].size += m[i].size; removeSeg(i); }
retryWaiting(0);
}
void compact(void) {
int i, k = 0, total = 0, used = 0;
for (i = 0; i < nblocks; i++) total += blockSize[i];
for (i = 0; i < nseg; i++)
if (m[i].owner != 0) {
m[k] = m[i]; m[k].size += m[k].waste; m[k].waste = 0; m[k].block = 0;
used += m[k].size; placedBlock[m[k].owner] = 0; k++;
}
nseg = k;
if (total > used) { m[nseg].block = 0; m[nseg].size = total - used; m[nseg].owner = 0; m[nseg].waste = 0; nseg++; }
nblocks = 1; blockSize[0] = total;
{ /* after compaction memory is one variable region: waiting processes take what they
need from the big hole (split), first come first served */
char saved = mode;
mode = 'S';
retryWaiting(1);
mode = saved;
}
}
int main(void) {
char cmd[4], s[4], md[4];
int i, x, pid = 0;
if (scanf("%d", &nblocks) != 1 || nblocks < 1 || nblocks > 10) { printf("BAD INPUT\n"); return 1; }
for (i = 0; i < nblocks; i++) {
if (scanf("%d", &blockSize[i]) != 1) { printf("BAD INPUT\n"); return 1; }
m[i].block = i; m[i].size = blockSize[i]; m[i].owner = 0; m[i].waste = 0;
}
nseg = nblocks;
if (scanf("%3s %3s", s, md) != 2) { printf("BAD INPUT\n"); return 1; }
scheme = s[0]; mode = md[0];
for (i = 0; i < 33; i++) placedBlock[i] = -1;
while (scanf("%3s", cmd) == 1) {
if (cmd[0] == 'A' && scanf("%d", &x) == 1 && pid < 32) {
int h = chooseHole(x);
pid++;
if (h < 0) { waitPid[nwait] = pid; waitSize[nwait] = x; nwait++; }
else place(pid, x, h);
} else if (cmd[0] == 'F' && scanf("%d", &x) == 1) freeProcess(x);
else if (cmd[0] == 'C') compact();
else { printf("BAD COMMAND\n"); return 1; }
}
for (i = 1; i <= pid; i++) if (placedBlock[i] >= 0) printf("P%d -> %d\n", i, placedBlock[i]);
printf("WAIT:");
for (i = 0; i < nwait; i++) printf(" P%d", waitPid[i]);
printf("\n");
for (i = 0; i < nseg; i++) printf("SEG: %d %d %d %d\n", m[i].block, m[i].size, m[i].owner, m[i].waste);
return 0;
}
Sample run · May 2026 Q12a, best fit · real output from gcc
Input (stdin)
6 200 400 600 500 300 250 B S A 357 A 210 A 468 A 491
Output (stdout)
P1 -> 1 P2 -> 5 P3 -> 3 P4 -> 2 WAIT: SEG: 0 200 0 0 SEG: 1 357 1 0 SEG: 1 43 0 0 SEG: 2 491 4 0 SEG: 2 109 0 0 SEG: 3 468 3 0 SEG: 3 32 0 0 SEG: 4 300 0 0 SEG: 5 210 2 0 SEG: 5 40 0 0
Cost
With an unsorted free list of k holes: first-fit O(k) worst case but usually stops early; best-fit and worst-fit always O(k). Keeping the list sorted by size speeds up the search but makes free() costlier.
Common mistakes
- Re-ordering the requests — they must be served in the given order.
- Forgetting that the leftover part of a block stays free.
- Calling external fragmentation ‘internal’.
Asked in KTU exams (2)
- November 2025 · Q12a6 marksConsider the requests from processes in given order 300K, 25K, 125K, and 50K. Let there be two blocks of memory available of size 150K followed by a block size 350K. Which of the memory allocation schemes can satisfy the above requests? Justify your answer.
- May 2026 · Q12a6 marksConsider six partition 200K, 400K, 600K, 500K, 300K and 250K and four processes blocks of size 357K, 210K, 468K and 491K. Which of the memory allocation schemes can satisfy the above requests? Justify your answer.
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
Exam-ready summary
- First-fit: first hole big enough. Best-fit: smallest big-enough hole. Worst-fit: largest hole.
- Leftover stays free; free() coalesces neighbours.
- Draw a table: request × scheme, show the leftover after every step, and state which schemes succeed.
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 4 (linked lists and dynamic storage: getNode / free, available-space lists)
- Silberschatz, Galvin & Gagne, Operating System Concepts — contiguous memory allocation
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)