Dynamic 2d array in C ++ and memory leaks
I wrote this code. It works fine, but when I test it under Valgrind, it catches 2 problems. Since I cannot interpret valgrind's messages, I would appreciate it if someone could explain me more and tell me where the problem is !!!
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;
}
a source to share
Ok, there are a couple of Valgrind warnings I get since 3.4, but only the first is important.
new / new [] failed and should throw an exception, but Valgrind cannot throw exceptions and therefore aborts instead. Unfortunately.
new
throws an exception if it doesn't work (unless you are using a newer version of newhrow). Unfortunately Valgrind doesn't handle this and refuses until your code is complete. Since valgrind is aborting, you are not writing code to free the memory, which shows up as a memory leak.
However, you are not handling the case of new throws, so your program will die from an unhandled exception if you run out of memory. You need to wrap your code with a try / except block.
a source to share
It seems to me that he is complaining that some of them new[]
fail. If you reduce the size height
and / or width
then it will work fine. You are probably trying to allocate too much memory.
EDIT . This is on my 32 bit field. If I run it on my 64 bit field, that's ok. So you will probably hit the memory limit on a 32-bit machine.
a source to share