我写了这段代码。它运行正常,但是当我在 Valgrind 下检查它时,它发现了 2 个问题。由于我无法解释 valgrind 的消息,如果有人能向我解释更多并告诉我问题出在哪里,我将不胜感激!!!
代码如下:
#include <iostream>
#define width 70000
#define height 10000
using namespace std;
int main(void)
{
int** pint;
pint = new int*[height];
for(int i = 0; i < height; i++)
pint[i] = new int[width];
for(int i = 0; i < height; i++){
delete[] pint[i];
pint[i] = NULL;
}
delete[] pint;
pint = NULL;
return 1;
}
最佳答案
好的,我在 3.4 中收到了几个 Valgrind 警告,但只有第一个是重要的。
new/new[] failed and should throw an exception, but Valgrind cannot throw exceptions and so is aborting instead. Sorry.
new
在内存不足时抛出异常(除非你使用 new 的 nothrow 版本)。不幸的是,Valgrind 无法处理并在您的代码完成之前放弃。因为 valgrind 中止,您释放内存的代码永远不会执行,这显示为内存泄漏。
也就是说,您没有处理 new throws 的情况,因此如果内存不足,您的程序将由于未处理的异常而终止。您需要用 try/except block 包装您的代码。
关于c++ - C++中的动态二维数组和内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2726012/