Let us learn how to implement Worst Fit Algorithm in C programming language. The memory management program for Worst Fit Algorithm uses Arrays.
What is Worst Fit Algorithm?
The Worst Fit Memory Allocation Algorithm allocates the largest free partition available in the memory that is sufficient enough to hold the process within the system.
It searches the complete memory for available free partitions and allocates the process to the memory partition which is the largest out of all.
This algorithm is not recommended to be implemented in the real world as it has many disadvantages.
A process entering first may be allocated the largest memory space but if another process of larger memory requirement is to be allocated, space cannot be found. This is a serious drawback here.
C Program To Implement Worst Fit Algorithm in OS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #include<stdio.h> int main() { int fragments[10], blocks[10], files[10]; int m, n, number_of_blocks, number_of_files, temp, top = 0; static int block_arr[10], file_arr[10]; printf("\nEnter the Total Number of Blocks:\t"); scanf("%d",&number_of_blocks); printf("Enter the Total Number of Files:\t"); scanf("%d",&number_of_files); printf("\nEnter the Size of the Blocks:\n"); for(m = 0; m < number_of_blocks; m++) { printf("Block No.[%d]:\t", m + 1); scanf("%d", &blocks[m]); } printf("Enter the Size of the Files:\n"); for(m = 0; m < number_of_files; m++) { printf("File No.[%d]:\t", m + 1); scanf("%d", &files[m]); } for(m = 0; m < number_of_files; m++) { for(n = 0; n < number_of_blocks; n++) { if(block_arr[n] != 1) { temp = blocks[n] - files[m]; if(temp >= 0) { if(top < temp) { file_arr[m] = n; top = temp; } } } fragments[m] = top; block_arr[file_arr[m]] = 1; top = 0; } } printf("\nFile Number\tFile Size\tBlock Number\tBlock Size\tFragment"); for(m = 0; m < number_of_files; m++) { printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", m, files[m], file_arr[m], blocks[file_arr[m]], fragments[m]); } printf("\n"); return 0; } |
Output

If you have any doubts or compilation errors in this C program to implement Worst Fit Memory Segment Algorithm in operating system, let us know about it in the comment section below.
Nice code for memory management in C programming.
Thanks for the explanation. It helped to understand the concept in a better way.
As the name sounds, the worst fit algorithm is not preferred at all.