Worst Fit Algorithm Program in C++

Worst Fit algorithm in OS

Worst Fit Algorithm Program in C++

The operating system, also known as the resource allocator is responsible for allocating memory to the process in execution. The process demands free memory block from the CPU during their execution.

How does Worst Fit work?

In the case of the worst fit when accommodating a process P1, the operating system searches for –

    • Memory block that can fit the process
    • Leaves the highest wasted(empty) space after P1 is placed in block
Worst Fit Allocation in OS Working

Program code for Worst Fit Memory management Scheme using C++

#include<bits/stdc++.h> 
using namespace std; 
  
// Program code to allocate empty memory to the process as oer the worst fit memeory allocation
void worstFit(int b_size[], int m, int p_size[], int n) 
{ 
     
    //code to store the memory id of the empty memory allocated to a process
   
     int allocation[n]; 

  
    // no memory is allocated at the initial stage
    memset(allocate, -1, sizeof(allocate)); 
  
    // select each process to search a suitable empty memory block for memeory allocation
    // empty memory assignment is also carried out in this code 
    for (int i=0; i<n; i++) 
    { 
        // Code to find the worst fit memory block
        int wstIdx = -1; 
        for (int j=0; j<m; j++) 
        { 

   
            if (b_size[j] >= p_size[i]) 
            { 
                if (wstIdx == -1) 
                    wstIdx = j; 
                else if (b_size[wstIdx] < b_size[j]) 
                    wstIdx = j; 
            } 
        } 
  
        // to search the empty memory block for the current process
   
        if (wstIdx != -1) 
        { 
            // allocate block j to p[i] process 
            allocate[i] = wstIdx; 
  
            // Reduce available memory in this block. 
            B_size[wstIdx] -= p_size[i]; 
        } 
    } 

  
   
    cout << "\nProcess Number \tProcess Size\tBlock Number\n"; 
    for (int i = 0; i < n; i++) 
    { 
 
        cout << "   " << i+1 << "\t\t" << p_size[i] << "\t\t"; 

   
        if (allocate[i] != -1) 

   
            cout<< allocate[i] + 1; 


        else
   
            cout << "Not Allocated"; 
        cout << endl; 
    } 
} 
  
// Driver code 
   
int main() 
{ 
    int blockSize[] = {100, 500, 200, 300, 600}; 
    int processSize[] = {212, 417, 112, 426}; 
    int m = sizeof(blockSize)/sizeof(blockSize[0]); 
    int n = sizeof(p_size)/sizeof(p_size[0]); 
  
    worstFit(b_size, m, p_size, n); 
  
    return 0 ; 
} 

Output

Process Number Process Size Block Number
1 2125
24172
31125
4426Not Allocated