MIT-Curricular/OS/C/Week9/q1-smol.c
2025-04-11 08:30:13 +05:30

81 lines
1.8 KiB
C

#include <stdio.h>
#include <stdlib.h>
#define BLOCKS 4
#define REQUESTS 5
// Memory configuration
int memory[BLOCKS] = {100, 50, 25, 10};
int allocated[BLOCKS] = {0, 0, 0, 0};
// Helper: Reset allocation state
void resetAllocation() {
for(int i = 0; i < BLOCKS; i++) {
allocated[i] = 0;
}
}
// Print memory status
void printMemory() {
printf("\nMemory Status:\n");
for(int i = 0; i < BLOCKS; i++) {
printf("[Size: %d, %s] -> ", memory[i],
allocated[i] ? "Allocated" : "Free");
}
printf("NULL\n\n");
}
// First Fit allocation
void firstFit(int size) {
for(int i = 0; i < BLOCKS; i++) {
if (!allocated[i] && memory[i] >= size) {
allocated[i] = 1;
printf("Allocated %d bytes using First Fit\n", size);
return;
}
}
printf("First Fit: No suitable block found for %d bytes\n", size);
}
// Best Fit allocation
void bestFit(int size) {
int best = -1;
int bestSize = 999999;
for(int i = 0; i < BLOCKS; i++) {
if(!allocated[i] && memory[i] >= size && memory[i] < bestSize) {
bestSize = memory[i];
best = i;
}
}
if(best != -1) {
allocated[best] = 1;
printf("Allocated %d bytes using Best Fit\n", size);
} else {
printf("Best Fit: No suitable block found for %d bytes\n", size);
}
}
// Main function: run allocation sequence
int main() {
int requests[REQUESTS] = {15, 35, 60, 10, 5};
printf("=== FIRST FIT ===\n");
printMemory();
for(int i = 0; i < REQUESTS; i++) {
firstFit(requests[i]);
printMemory();
}
resetAllocation();
printf("=== BEST FIT ===\n");
printMemory();
for(int i = 0; i < REQUESTS; i++) {
bestFit(requests[i]);
printMemory();
}
return 0;
}