C++内存管理中最佳适配算法程序
给定两个包含块大小和进程大小的数组;任务是根据内存管理中的最佳适配算法打印结果。
什么是最佳适配算法?
最佳适配是一种内存管理算法;它处理分配满足请求进程需求的最小空闲分区。在这种算法中,我们查找整个内存块并检查最适合进程的最小块,然后查找可用于满足适当进程的紧邻块。
因此,我们将获取块大小和进程大小,并返回进程的输出以及要分配给进程的块。
示例
Input: bsize[] = {100, 500, 200, 300, 400} psize[] = {112, 518, 110, 526} Output: Process No. Process Size Block no. 1 112 3 2 518 Not Allocated 3 110 4 4 526 Not Allocated
将使用的方法来解决上述问题 -
- 获取进程和块大小的输入。
- 最初将所有内存块设置为空闲。
- 获取每个进程并找到可以分配给块的最小块大小,这意味着大于进程大小的整个块的最小值。
- 如果找到,则将其分配给当前进程,否则放弃该进程并检查后续进程。
算法
Start Step 1-> In function void bestfit(int bsize[], int m, int psize[], int n) Declare int alloc[n] Call function memset(alloc, -1, sizeof(alloc)) Loop For i=0 and i<n and i++ Declare and Initialize bestIdx = -1 Loop For j=0 and j<m and j++ If bsize[j] >= psize[i] then, If bestIdx == -1 then, Set bestIdx = j Else If bsize[bestIdx] > bsize[j] then, Set bestIdx = j If bestIdx != -1 then, Set alloc[i] = bestIdx Set bsize[bestIdx] -= psize[i] Loop For i = 0 and i < n and i++ Print i+1, psize[i] If alloc[i] != -1 Print alloc[i] + 1 Else Print "Not Allocated" Print newline Step 2->In function int main() Declare and initialize bsize[] = {100, 500, 200, 300, 400} Declare and initialize psize[] = {112, 518, 110, 526} Set m = sizeof(bsize)/sizeof(bsize[0]) Set n = sizeof(psize)/sizeof(psize[0]) Call function bestfit(bsize, m, psize, n) Stop
示例
#include <iostream> #include <memory> using namespace std; // To allocate the memory to blocks as per Best fit // algorithm void bestfit(int bsize[], int m, int psize[], int n) { // To store block id of the block allocated to a // process int alloc[n]; // Initially no block is assigned to any process memset(alloc, -1, sizeof(alloc)); // pick each process and find suitable blocks // according to its size ad assign to it for (int i=0; i<n; i++) { // Find the best fit block for current process int bestIdx = -1; for (int j=0; j<m; j++) { if (bsize[j] >= psize[i]) { if (bestIdx == -1) bestIdx = j; else if (bsize[bestIdx] > bsize[j]) bestIdx = j; } } // If we could find a block for current process if (bestIdx != -1) { // allocate block j to p[i] process alloc[i] = bestIdx; // Reduce available memory in this block. bsize[bestIdx] -= psize[i]; } } cout << "\nProcess No.\tProcess Size\tBlock no.\n"; for (int i = 0; i < n; i++) { cout << " " << i+1 << "\t\t\t\t" << psize[i] << "\t\t\t\t"; if (alloc[i] != -1) cout << alloc[i] + 1; else cout << "Not Allocated"; cout << endl; } } // Driver code int main() { int bsize[] = {100, 500, 200, 300, 400}; int psize[] = {112, 518, 110, 526}; int m = sizeof(bsize)/sizeof(bsize[0]); int n = sizeof(psize)/sizeof(psize[0]); bestfit(bsize, m, psize, n); return 0 ; }
输出
Process No. Process Size Block no. 1 112 3 2 518 Not Allocated 3 110 4 4 526 Not Allocated
广告