So during a code review, a colleague of mine used a double* d = new double[foo];
and then called delete d
. I told them that they should change it to delete [] d
. And they stated that the compiler doesn't need that for basic data types. I disagreed.
So I thought I'd prove my point with an experiment:
#define NUM_VALUES 10000
int main(int argc,char** argv)
{
int i = 0;
while (true)
{
std::cout << i << "|";
double* d = new double[NUM_VALUES];
std::cout << ((void*)d) << std::endl;
for (int j = 0; j < NUM_VALUES; j++)
d[j] = j;
delete d;
i++;
}
return 0;
}
Not only does the memory usage not grow, but d is allocated to the same place every time! (Visual Studio 2010). Is this a quirk of the visual studio compiler? Or is this part of the standard?
If you use new
you need to use delete
If you use new []
you have to use delete []
They mean different things. double* d = new double();
means allocate and construct a double type. delete d;
means unallocated and destruct a single double type. double* d = new double[NUM_VALUES];
means allocate NUM_VALUES
doubles and delete [] d
means unallocated each of of the NUM_VALUES
doubles allocated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With