BobAlmond
BobAlmond

Reputation: 903

Heap Error in C++

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...

Upvotes: 2

Views: 2896

Answers (3)

sharptooth
sharptooth

Reputation: 170489

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.

Upvotes: 1

Patrick
Patrick

Reputation: 23619

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.

Upvotes: 0

anon
anon

Reputation:

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
}

Upvotes: 5

Related Questions