PDA

View Full Version : memory allocation problem



marc2050
20th May 2011, 04:57
Hi.

I do a memory allocation using 'new', as follow.


double *myarray[50];
for (int j = 0; j < 50; j++)
myarray[j] = new double[100000];

When the codes first run it works. When I rerun it, (e.g. when user click the button again) the program crash. I tried to debug but couldnt find an answer. What is the right way to "trap" such memory allocation codes in QT? And is there a better way to allocate an array of pointers to double in QT?

I also delete the allocation as needed by the following codes

for (int j = 0; j < 50; j++)
delete [] myarray[j]

Thanks!

Lykurg
20th May 2011, 06:30
Ehm, that has nothing to do with Qt. It is all about basic C++. See any C++ reference, e.g. http://www.fredosaurus.com/notes-cpp/newdelete/50dynamalloc.html.


And next time please use code tags when posting source code.

ChrisW67
20th May 2011, 06:59
You "trap" program crashes with a debugger and then look at a backtrace of calls until you find your culprit. How you do that depends on your tool chain and is nothing to do with Qt. Depending on exception handlers in your code a failure to allocate space with new or new[] will terminate your program.

You could use nested QVector or std::vector structures and save yourself the memory management but they may allocate more storage than you require because they allow for resizing.

high_flyer
20th May 2011, 11:36
hen I rerun it, (e.g. when user click the button again) the program crash.
In addition to the previous posters, you are allocating a very large amount of memory (20MB per loop execution).
If this code is running on an embedded system for example, it is possible you are running out of memory especially if you didn't delete the previous allocation.
Not deleting the previous allocation before the new allocation happens, also can cause your application to crash.
If 'new' fails, it returns NULL.
Thus you can check your allocation before continuing, and handling the case gracefully instead of having the application crash on the assumption that allocation was successful.

DanH
20th May 2011, 12:10
My guess is that you're never getting to the delete, and the second time through there isn't another 20 mb to be had in the heap.

Santosh Reddy
20th May 2011, 18:22
What was you debugging observations ?
You need have some kind of exception handling, when dealing such big memory allocations.

ChrisW67
21st May 2011, 02:20
Doubles are 8 bytes, by 50 sets of 100,000 is 40,000,000 bytes to allocate (in contiguous blocks of 800,000 bytes)

high_flyer
23rd May 2011, 09:05
Doubles are 8 bytes
Ah... true, sorry. :)