Next Fit in C++
Definition
Next fit is another version of First Fit in which memory is searched for empty spaces similar to the first fit memory allocation scheme. Unlike first-fit memory allocation, the only difference between the two is, in the case of next fit, if the search is interrupted in between, the new search is carried out from the last location.
C++ Program for Next Fit Memory Management
// C++ implementation code for next fit memory allocation scheme
#include <bits/stdc++.h>
using namespace std;
// Method to assign memory to a block using the next fit memory allocation scheme
void NextFit(int b_size[], int m, int p_size[], int n)
{
//code to store block id of a block to a process demanding memory
int allocation[n], j = 0;
// No process is assigned with memory at the initial phase
memset(allocate, -1, sizeof(allocate));
// pick each process and find suitable blocks
// according to its size ad assign to it
for (int i = 0; i < n; i++) {
// Condition to control memory search not from the beginning
while (j < m) { if (b_size[j] >= p_size[i]) {
// code to assign block j to p[i] process
allocation[i] = j;
// Reduce available memory in this block.
blockSize[j] -= processSize[i];
break;
}
// mod m will help to traverse the free memory blocks from the first block when it reaches end
j = (j + 1) % m;
}
}
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 program
int main()
{
int b_size[] = { 5, 10, 20 };
int p_size[] = { 10, 20, 5 };
int m = sizeof(b_size) / sizeof(b_size[0]);
int n = sizeof(p_size) / sizeof(p_size[0]);
NextFit(b_size, m, p_size, n);
return 0;
}
Output
Process Number Process Size Block Number 1 10 2 2 20 3 3 5 1

Login/Signup to comment