Lab 11 walkthrough — Memory allocation strategies: First Fit, Best Fit, Worst Fit
Lab 11 walkthrough — Memory allocation strategies: First Fit, Best Fit, Worst Fit
Recorded by Dr. Krithika L.B. Slot lab11-walkthrough
Theory link: 4.2 Contiguous allocation
Lab 11 walkthrough — Memory allocation strategies: First Fit, Best Fit, Worst Fit
Recorded by Dr. Krithika L.B. Slot lab11-walkthrough
Aim. To allocate memory blocks to processes using the First Fit, Best Fit and Worst Fit strategies and report the leftover hole for each allocation.
For each process (in order), scan the blocks and pick one whose free space ≥ the process size (Session 4.2):
The first block that fits — stop searching.
The block with the smallest free space that fits.
The block with the largest free space.
The chosen block's free space shrinks by the process size, so later processes can use the leftover (variable partitions). A process that fits nowhere must wait — external fragmentation.
/* fit.c - memory allocation strategies: First Fit, Best Fit, Worst Fit (BACSE106 Lab 11) */
#include <stdio.h>
int main(void)
{
int nb, np, choice, i, j;
int block[20], left[20], proc[20], alloc[20], hole[20];
printf("Number of memory blocks: ");
scanf("%d", &nb);
printf("Block sizes: ");
for (i = 0; i < nb; i++) scanf("%d", &block[i]);
printf("Number of processes: ");
scanf("%d", &np);
printf("Process sizes: ");
for (i = 0; i < np; i++) scanf("%d", &proc[i]);
printf("1.First Fit 2.Best Fit 3.Worst Fit Choice: ");
scanf("%d", &choice);
for (i = 0; i < nb; i++) left[i] = block[i]; /* free space in each block */
for (i = 0; i < np; i++) {
int k = -1;
for (j = 0; j < nb; j++) {
if (left[j] < proc[i]) continue; /* too small */
if (k == -1) { k = j; if (choice == 1) break; continue; } /* first fit stops at the first */
if (choice == 2 && left[j] < left[k]) k = j; /* best: smallest that fits */
if (choice == 3 && left[j] > left[k]) k = j; /* worst: largest */
}
alloc[i] = k;
if (k != -1) { left[k] -= proc[i]; hole[i] = left[k]; } /* hole left right after this allocation */
}
printf("\nProcess Size Block Block size Hole left\n");
for (i = 0; i < np; i++) {
if (alloc[i] == -1)
printf("P%-7d %-5d Not allocated (must wait)\n", i + 1, proc[i]);
else
printf("P%-7d %-5d B%-5d %-11d %d\n", i + 1, proc[i], alloc[i] + 1, block[alloc[i]], hole[i]);
}
return 0;
}gcc fit.c -o fit./fitProcess Size Block Block size Hole left
P1 212 B2 500 288
P2 417 B5 600 183
P3 112 B2 500 176
P4 426 Not allocated (must wait)Process Size Block Block size Hole left
P1 212 B4 300 88
P2 417 B2 500 83
P3 112 B3 200 88
P4 426 B5 600 174Process Size Block Block size Hole left
P1 212 B5 600 388
P2 417 B2 500 83
P3 112 B5 600 276
P4 426 Not allocated (must wait)Prepare these for the lab evaluation.
Revealed 0First Fit — it stops at the first suitable block.
External fragmentation: no single block had 426 KB free.
Best Fit.
Compaction (needs dynamic relocation) or non-contiguous allocation (paging/segmentation).