gpt4 book ai didi

c++ - 如何检查是否有足够的可用堆内存?

转载 作者:可可西里 更新时间:2023-11-01 16:36:26 26 4
gpt4 key购买 nike

我有一项任务要求我创建一个分配和释放内存的“堆”类。我相信我的代码可以正常工作并且解决方案可以正常构建和运行,但我想确保我没有遇到任何内存泄漏。我还需要添加一些代码来检查分配给堆的所需数量是否可用……如果有人要分配非常大的数量。如果没有足够的内存,如何检查堆上分配的内存是否可用或 NULL。到目前为止,这是我的代码:

#include <iostream>
using namespace std;

class Heap{
public:

double* allocateMemory(int memorySize)
{
return new double[memorySize];
};
void deallocateMemory(double* dMemorySize)
{
delete[] dMemorySize;
};

};

int main()
{
Heap heap;
cout << "Enter the number of double elements that you want to allocate: " << endl;
int hMemory;
const int doubleByteSize = 8;
cin >> hMemory;

double *chunkNew = heap.allocateMemory(hMemory);

cout << "The amount of space you took up on the heap is: " <<
hMemory*doubleByteSize << " bytes" <<
starting at address: " << "\n" << &hMemory << endl;

heap.deallocateMemory(chunkNew);

system("pause");
return 0;
}

最佳答案

没有必要事先检查,只是尝试分配内存,如果不能,则捕获异常。在本例中,它是 bad_alloc 类型。

#include <iostream>
#include <new> // included for std::bad_alloc

/**
* Allocates memory of size memorySize and returns pointer to it, or NULL if not enough memory.
*/
double* allocateMemory(int memorySize)
{
double* tReturn = NULL;

try
{
tReturn = new double[memorySize];
}
catch (bad_alloc& badAlloc)
{
cerr << "bad_alloc caught, not enough memory: " << badAlloc.what() << endl;
}

return tReturn;
};

重要提示

一定要防止双重释放内存。一种方法是通过引用将指针传递给 deallocateMemory,允许函数将指针值更改为 NULL,从而防止 delete 的可能性-ing 指针两次。

void deallocateMemory(double* &dMemorySize)
{
delete[] dMemorySize;
dMemorySize = NULL; // Make sure memory doesn't point to anything.
};

这可以防止出现如下问题:

double *chunkNew = heap.allocateMemory(hMemory);
heap.deallocateMemory(chunkNew);
heap.deallocateMemory(chunkNew); // chunkNew has been freed twice!

关于c++ - 如何检查是否有足够的可用堆内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16158981/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com