Aim:
To write a C Program to Implement the Memory Management Scheme Using Best Fit.
Algorithm:
- Best Fit Algorithm
- Get no. of Processes and no. of blocks.
- After that get the size of each block and process requests.
- Then select the best memory block that can be allocated using the above definition.
- Display the processes with the blocks that are allocated to a respective process.
- Value of Fragmentation is optional to display to keep track of wasted memory.
- Stop.
Exercise:
- Given memory partition of 100 KB, 500 KB, 200 KB, 300 KB and 600 KB (in order), how would each of the first-fit, best fit and worst fit algorithms place processes of 212 KB, 417 KB, 112 KB and 426 KB (in order)? Which algorithm makes the most efficient use of memory? Either it is best fit.
Program:
#include<stdio.h> #include<stdlib.h> #include<stdbool.h> struct p{ int acum[100]; int jp[100]; }st; int main() { int n,m,i,count=0,j,pn[100]; int p[100],size[100]; bool flag[100]; printf("ENTER THE NO PROCESS AND MEMORY :\n "); scanf("%d%d",&n,&m); printf("ENTER THE SIZE OF PROCESS \n"); for(i=0;i<n;i++) scanf("%d",&p[i]); printf("ENTER THE SIZE OF MEMORY PARTION \n"); for(i=0;i<m;i++) { scanf("%d",&size[i]); flag[i]=0; } for(i=0;i<n;i++) { int ic=0,in=0; for(j=0;j<m;j++) { if(p[i]<=size[j]&&flag[j]==0) { int k; st.acum[in]=size[j]; st.jp[in]=j; in++; ic++; for(k=ic-1;k>0;k--) { if(st.acum[k]<=st.acum[k-1]) { int temp=st.acum[k]; st.acum[k]=st.acum[k-1]; st.acum[k-1]=temp; temp=st.jp[k]; st.jp[k]=st.jp[k-1]; st.jp[k-1]=temp; } } } } if(ic>0) { j=st.jp[0]; flag[j]=true; pn[j]=i; count++; } } printf("NO OF PROCESS CAN ACOMADATE :%d\n\n",count); printf("MEMORY\tPROCESS\n"); for(i=0;i<m;i++ ) { if(flag[i]==1) { printf("%d <-->%d\n",size[i],p[pn[i]]); } else printf("%d\tMEMORY NOT ALLOCATED\n",size[i]); } return 0; }
Execution:
Input: 4 5 212 417 112 426 100 500 200 300 600 Output: ENTER THE NO PROCESS AND MEMORY : ENTER THE SIZE OF PROCESS ENTER THE SIZE OF MEMORY PARTION NO OF PROCESS CAN ACOMADATE :4 MEMORY PROCESS 100 MEMORY NOT ALLOCATED 500 <-->417 200 <-->112 300 <-->212 600 <-->426
Result:
Thus Memory Management Scheme using the Best Fit program was executed Successfully.