Best Fit Algorithm Program In C

Memory allocation is one of the important tasks of the operating system. As the different processes need the CPU processing time, they also need a certain amount of memory. This memory is allocated to different processes according to their demand. The three most common types of memory allocation schemes are the best fit, first fit, and worst fit.

In the case of the best fit memory allocation scheme, the operating system searches for the empty memory block. When the operating system finds the memory block with minimum wastage of memory, it is allocated to the process. This scheme is considered as the best approach as it results in most optimised memory allocation. However, finding the best fit memory allocation may be time-consuming.

 

Program in C for Best Fit

#include
 
// main function
void main()
{
	// declaration and initialization of variables
 	int fragment[20],b[20],p[20],i,j,nb,np,tem,low=9999;
	static int barray[20],parray[20];
	

	printf("Memory Management Scheme - Best Fit");
	
 	//input number of processes

 	printf("Enter the number of processes:");


	scanf("%d",&n_p);

 	//input number of blocks

 	printf("\nEnter the number of blocks:");

	scanf("%d",&n_b);
	
	//input number of blocks

 	printf("\nEnter the size of the blocks:-\n");
	for(i=1;i<=n_b;i++)
    	{

		printf("Block no.%d:",i);

         		scanf("%d",&b[i]);
     	}
	
	//input the size of process

 	printf("\nEnter the size of the processes :-\n");
	for(i=1;i<=n_p;i++)
    {

        printf("Process no.%d:",i);

        scanf("%d",&p[i]);
    }
	
	for(i=1;i<=n_p;i++)
	{
		for(j=1;j<=n_b;j++)
		{

			if(barray[j]!=1)
			{
				tem=b[j]-p[i];
				if(tem>=0)
					if(low>temp)
					{
						parray[i]=j;
						low=tem;
					}
			}
		}

		
		fragment[i]=low;
		barray[parray[i]]=1;
		low=10000;
	}
	
	//Print the result

printf("\nProcess_number \tProcess_size\tBlock_number \tBlock_size\tFragment");
	for(i=1;i<=np && parray[i]!=0;i++)

		printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,p[i],parray[i],b[parray[i]],fragment[i]);
}

Output


Enter the number of blocks: 5
Enter the number of processes: 4
Enter the size of the blocks:
Block number 1: 10
Block number 2: 15
Block number 3: 5
Block number 4: 9?
Block number 5: 3
Enter the size if the process
Process number 1: 1
Process number 2: 4
Process number 3: 7
Process number 4: 12

Process numberProcess sizeBlock number Block sizeFragment
11532
24351
37492
4122153

Process returned 4 (0 x4) execution time: 33. 196 s

Please Login/Signup to comment