I’ve heard that you should usually “delete” whenever you use “new”, yet when I run a simple test program (below), it doesn’t seem to make a difference which numbers I put for arraySize or numLoops. Does this cause a memory leak?
#include <iostream>
int main()
{
double *array;
const int arraySize = 100000;
const int numLoops = 100000;
for (int i = 0; i < numLoops; i++)
{
// do I need to call "delete [] array;" here?
array = new double[arraySize];
}
int x;
std::cin >> x; // pause the program to view memory consumption
delete [] array;
return 0;
}
No, it’s not sufficient.
Each time you call
newornew[], some memory is allocated, and you are given the address of that memory (in order to be able to use it). Each piece of memory must eventually bedeleted (ordelete[]d).You are storing that address in
array, but then immediately overwriting it on the next iteration. Therefore you have no way ofdelete-ing all of pieces of memory that you’ve been allocated. Therefore you have a memory leak.