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. In such a case, the memory is allocated from the primary memory using some specific schemes. The most common schemes include first fit, best fit and worst fit.

In the case of the worst fit memory allocation scheme, the memory is allocated without considering the best case, i.e., causing maximum memory wastage. The memory block is allocated to the process as soon as it finds an empty memory slot equal to or greater than the demanded memory by the process. This memory allocation is carried out following an algorithm, also known as the scheduling algorithm.

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

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; 

            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 ; 



Process Number Process Size Block Number
1 2125
4426Not Allocated

Please Login/Signup to comment