views:

62

answers:

3
+1  Q: 

Heap Error in C++

Dear all,

I'm a beginner programmer in C++. Recently, I'm working on image processing thing using C++.

but I have some problem that I want to ask. Suppose I have some code as follow:

for (int i=0;i<100000;i++)
{
  int * a = new int[10000];
  //do something
  delete [] a;
}

When I executed that code, I receive runtime error, Heap Error...

Is there anything wrong with that code, I mean, can I allocate memory and release it in the same loop?

Thanks in advance...

+5  A: 

Probably the error is in the code you are not showing. You might also want to re-write the code like this:

int * a = new int[10000];
for (int i=0;i<100000;i++)
{
  //do something
}
delete [] a;

which if nothing else will be far more efficient. And as this is C++, you might also consider:

vector <int> a( 10000 );
for (int i=0;i<100000;i++)
{
  //do something
}
anon
In pretty much all modern compilers, moving the allocation (and deletion) out of the loop won't make any difference as far as performance is concerned. On the other hand, if the array "logically" belongs in the loop, then it's generally better to leave it there.
Tal Pressman
@Tal Memory allocation always has a performance cost, no matter how "modern" the compiler. And it's not obvious to me that the array does belong in the loop.
anon
First, assuming the code really is as simple as posted, then the compiler will most likely optimize all the allocations away.Second, since the array is allocated and disposed of in the loop, then logically it doesn't belong outside of it.In any case, moving the allocation outside of the loop introduces a possible bug, if the "do something" part assumes the array is initialized to 0.
Tal Pressman
@Tal I've never come across a compiler that can "optimise away" dynamic memory allocations - which one do you know that does? As to your second point - the fact that this beginner programmer has placed the allocation in the loop in no way proves that it logically belongs there. And dynamically allocated arrays are not initialised to zero, so such an assumption would be incorrect.
anon
@Tal: To make it initialize to 0s you need `new char[size]()` - see http://stackoverflow.com/questions/2468203/how-can-i-make-new-default-initialize-the-array-of-primitive-types
sharptooth
A: 

The code in between the new and delete probably overwrites part of memory before or after the allocated memory. This is called a memory overwrite (underflow or overflow).

Check the code to see if you don't accidentally e.g. write at index 10001 (or even 10000 is incorrect). The maximum index is 9999.

Patrick
+1  A: 

The problem is likely in the "do something". Most likely you write outside the array and this leads to heap corruption.

Other than that allocating and freeing memory in the same loop iteration is okay but makes little sense - since the number of elements is constant you could just as well allocate before the loop and free after the loop.

sharptooth