Consider the code (it has no meaningful purpose):
double* create() {
double *array = new double[100]; // 1)
for(unsigned int i=0; i<100; ++i) array[i] = i;
return array;
}
double reduce(double* array) {
double sum = 0.0;
for(unsigned int i=0; i<100; ++i) sum += array[i];
return sum;
}
int main()
{
double sum = 0.0;
for(unsigned int i=0; i<100; ++i) {
sum += reduce(create());
}
// 2)
// ...
}
Are the arrays created in 1) during the for-loop still on the heap at point 2) i.e. is some memory still being (unnecessarily) occupied at point 2)?
(I know that the example could be more minimalistic but it is really short.)
The array is still in the heap but the pointer to the array is lost. As a result there is a memory leak.
So you should split the calls of the functions introducing a variable that will store the pointer returned from the function create that then you could use the variable to free the allocated array.
That is the array with the dynamic storage duration will be destroyed when the operator delete [] will be called. Or the memory will be freed when the program will finish its execution.