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
Two questions, two answers.
Question one: Does calling new [] twice on the same pointer without calling delete [] in between cause a memory leak?
Answer one: Not always, but 99% of the time yes. The code below calls new twice, with the pointer to array, but the first time it assigns the address of the allocated memory to array2, and the second time it keeps the address to itself. It is possible to delete both array in this scenario.
#include
int main()
{
double *array;
double *array2;
const int arraySize = 100000;
for (int i = 0; i < 2; i++)
{
// do I need to call "delete [] array;" here?
array = new double[arraySize];
if(i == 0)
{
array2 = array;
}
}
int x;
std::cin >> x; // pause the program to view memory consumption
delete [] array;
delete [] array2;
return 0;
}
Question Two: Is this usage of delete [] sufficient?
Answer Two: no, because the delete call only influences the address pointed to by the pointer you've given it. As you overwrote the pointer in your example, it deletes the last allocated section of memory