modified and updated
This commit is contained in:
parent
44e766514e
commit
6ff1894732
6 changed files with 674 additions and 7 deletions
81
OS/C/Week9/q1-smol.c
Normal file
81
OS/C/Week9/q1-smol.c
Normal file
|
@ -0,0 +1,81 @@
|
|||
#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;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue