简体   繁体   中英

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. Since I can not interpret valgrind's messages i will appreciate if anyone explain me more and tell me where is the problem!!!

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.

new/new[] failed and should throw an exception, but Valgrind cannot throw exceptions and so is aborting instead. Sorry.

new throws an exception when it is out of memory (unless you use the nothrow version of new). Unfortunately, Valgrind cannot handle that and gives up before your code completes. Because valgrind aborts, you code to free up memory is never executed which shows up as memory leaks.

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.

It looks to me like it's complaining that some of the new[] s are failing. If you reduce the size of height and/or width , then it works fine. You're likely trying to allocate too much memory.

EDIT : That's on my 32-bit box. If I run it on my 64-bit box, it's fine. So, you're likely hitting a memory limit on a 32-bit machine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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