views:

26

answers:

2

Hello everyone,

If i create a heap array inside a loop, do i have to delete it at the end of each loop before i reinitialize it at the beginning of the loop again or will reinitializing the exact same thing again simply overwrite the old array and i can just skip the delete command?

+1  A: 

Do you mean something like this?

for (int i = 0; i < 5; i++) {
    char *array = new char[10];
    // ...
    delete[] array;
}

In that case: yes, you do need to delete the array.

If you had written something like this instead,

char *array = 0;
for (int i = 0; i < 5; i++) {
    if (!array) array = new char[10];
    // ...
}
delete[] array;

then no, you can reuse the array across multiple iterations of the loop.

ephemient
I'm sure you realize that the 2nd example (as it's written) leaks memory. For clarity, I'll emphasize that the line `if (!array) array = new char[10];` should be moved above the loop, thus enabling re-use of the array.
Dan Breslau
How does it leak memory? Once the array is allocated, `!array` is false, so it is only allocated once. And `delete[]` works on both NULL and an allocated array. The reason I put it in the loop to begin with is so that nothing is allocated if there are zero iterations, but if it is always necessary to allocate memory it would indeed make more sense to do so outside of the loop.
ephemient
D'oh. Right. Sorry.
Dan Breslau
A: 

Adding to ephemient's answer: Why are you thinking about re-initializing the array inside of the loop?

Your question would be appropriate if every iteration of your loop needs to do both of these steps:

1) Insert data into the array.

2) Do something with the data that's been filled into the array

If this doesn't sound like what your code needs to do, then the answer to your question should probably be: Don't create or delete the array inside the loop. Create the array before the loop, and delete it afterwards.

(In my experience, it's rare to find a case where steps 1) and 2) are done within the same loop.)

Dan Breslau
Im doing operations on a 3D object, first in the Z axis (which i need to create an array that includes only sections at that z height), next in the y axis (taking the previously generated array and further reducing it) and finally in the x axis (which operates on the last reduced list).
Faken
Okay... but to me that suggests three different loops, and perhaps more than one array... but I'll take your word for it.
Dan Breslau