First Fit program in C++

Memory management schemes in an operating system are used to allocate memory during the processing time. These schemes allocate memory chunks to the processes based on different criteria. The three most commonly used schemes are first fit, best fit, and worst fit.

Among all the above-mentioned schemes, the first fit allocates the memory segment to the first empty slot it finds in the memory. This is done by scanning the memory segments sequentially for an empty slot. When the processor finds a memory segment greater than or equal to the memory in demand, it is immediately allocated to the process. The system even allocates memory segments that are larger than the demand. Such an approach causes a considerable amount of memory wastage.

Read Also – First Fit algorithm in JAVA

Program for First Fit in  C++

#include

using namespace std;

  int main()

  {

//variable initialization and allocation

      int blocksize[10], processsize[10], blockno, processno, flags[10], allocation[10], i, j;

      for(i = 0; i < 10; i++)

   {

flags[i] = 0;

allocation[i] = -1;

}

      //entering blocks

       cout<<"Fill the number of blocks: ";


       cin>>blockno;

       cout<<"\nFill size of each block: ";

           for(i = 0; i < blockno; i++)


        cin>>blocksize[i];


//Entering processes

        cout<<"\nFill the number of processes: ";


        cin>>processno;


        cout<<"\nEnter each process size: ";

        for(i = 0; i < processno; i++)


        cin>>processsize[i];

//memory allocation as per first fit

         for(i = 0; i < processno; i++)

         for(j = 0; j < blockno; j++)

        if(flags[j] == 0 && blocksize[j] >= processsize[i])

    {

         allocation[j] = i;

         flags[j] = 1;

         break;

     }

 

//display allocation details


          cout<<"\nBlock no.\tsize\t\tprocess no.\t\tsize";

          for(i = 0; i < blockno; i++)

{

          cout<<"\n"<< i+1<<"\t\t"<<blocksize[i]<<"\t\t";


          if(flags[i] == 1)



          cout<<allocation[i]+1<<"\t\t\t"<<processsize[allocation[i]];

          else

          cout<<"Not allocated";

}


return 0;

} 


Output:
Enter the number of blocks: 3
Enter the size of each block: 12
7
4
Enter the number of processes: 3
Enter the size of each process: 7
4
9
Block no. Size Process No. Size
1 12 1 7
2 7 2 4
3 4 Not Allocated