Worst Fit Memory Allocation

int main(){
   
   int p,m;  
   printf("Enter number of processes:");
   scanf("%d",&p);
   printf("Enter number of Memory blocks:");
   scanf("%d",&m);
   
   int parr[p];
   struct mem{
          int id;
          int size;
   }marr[m];
   int i;
   for(i=0;i<p;i++)
   {
     printf("Enter size of process %d:",i+1);
     scanf("%d",&parr[i]);      
   }
   for(i=0;i<m;i++)
   {
     printf("Enter size of memory %d:",i+1);
     scanf("%d",&marr[i].size);   
     marr[i].id=i+1;   
   }
   int j;
   for(i=0;i<m;i++)
   for(j=i+1;j<m;j++)
   if(marr[i].size<marr[j].size)
   {
    struct mem t=marr[i];
    marr[i]=marr[j];
    marr[j]=t;                               
   }
   for(i=0;i<p;i++){
       for(j=0;j<m;j++){
         if(marr[j].size>=parr[i]){
              marr[j].size-=parr[i];
              printf("Allocating process %d to memory %d\n Size remaining in it after allocation %d\n\n",i+1,j+1,marr[j].size);   
              break;              
         }  
         
        
     }    
      if(j==m)
         {printf("Not enough memory for process %d",i);break;}        
   }
  getch();  
}

/*Output
Enter number of processes:5
Enter number of Memory blocks:6
Enter size of process 1:201
Enter size of process 2:49
Enter size of process 3:415
Enter size of process 4:127
Enter size of process 5:423
Enter size of memory 1:50
Enter size of memory 2:100
Enter size of memory 3:500
Enter size of memory 4:200
Enter size of memory 5:300
Enter size of memory 6:600
Allocating process 1 to memory 1
Size remaining in it after allocation 399

Allocating process 2 to memory 1
Size remaining in it after allocation 350

Allocating process 3 to memory 2
Size remaining in it after allocation 85

Allocating process 4 to memory 1
Size remaining in it after allocation 223

Not enough memory for process 4
*/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s