简体   繁体   English

c ++中的动态二维数组和内存泄漏

[英]Dynamic 2d array in c++ and memory leaks

I wrote this code. 我写了这段代码。 It runs OK, but when I check it under Valgrind it catches 2 problems. 它运行正常,但是当我在Valgrind下检查它时它会遇到2个问题。 Since I can not interpret valgrind's messages i will appreciate if anyone explain me more and tell me where is the problem!!! 既然我无法解释valgrind的消息,我会很感激,如果有人解释我更多,并告诉我问题在哪里!

Here is the code: 这是代码:

#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;
}

Okay, there are a couple of Valgrind warnings I get with 3.4 but only the first is important. 好吧,有一些Valgrind警告我得到3.4但只有第一个很重要。

new/new[] failed and should throw an exception, but Valgrind cannot throw exceptions and so is aborting instead. new / new []失败并且应该抛出异常,但Valgrind不能抛出异常,因此正在中止。 Sorry. 抱歉。

new throws an exception when it is out of memory (unless you use the nothrow version of new). new在内存不足时抛出异常(除非你使用new的nothrow版本)。 Unfortunately, Valgrind cannot handle that and gives up before your code completes. 不幸的是,Valgrind在代码完成之前无法处理并放弃。 Because valgrind aborts, you code to free up memory is never executed which shows up as memory leaks. 因为valgrind中止,所以从不执行代码来释放内存,这会显示为内存泄漏。

That said, you are not handling the case where new throws so your program will die due to an unhandled exception if you run out of memory. 也就是说,您没有处理新抛出的情况,因此如果内存不足,您的程序将因未处理的异常而死亡。 You need to wrap your code with a try/except block. 您需要使用try / except块包装代码。

It looks to me like it's complaining that some of the new[] s are failing. 在我看来,它正在抱怨一些new[]失败了。 If you reduce the size of height and/or width , then it works fine. 如果你减小height和/或width的大小,那么它工作正常。 You're likely trying to allocate too much memory. 你可能试图分配太多内存。

EDIT : That's on my 32-bit box. 编辑 :那是在我的32位盒子上。 If I run it on my 64-bit box, it's fine. 如果我在我的64位盒子上运行它,那很好。 So, you're likely hitting a memory limit on a 32-bit machine. 因此,您可能会在32位计算机上达到内存限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM