Indeed you are correct the destructors for each object in the array are not being called. So indeed delete without brackets would fail to free all memory.... but what if there is no need for a destructor? That is we never allocated memory inside the class object...
For example:
Code:
struct Test
{
int one;
float two;
};
The compiler knows that this structure is exactly 8 bytes in size unless overridden by the user for memory alignment in which case it still knows the exact size... this structure will never increase or decrease in size...
So:
Code:
int main()
{
Test *n = new Test[5];
delete n;
}
Will simply just call Malloc(40) and Free(40) will it not?
Step into the new() function... all I'm seeing is a malloc call..
I think this will result in zero memory leaks even though I'm not calling delete []...
For example try:
Code:
int main()
{
float *f = new float[5];
delete f;
}
Debug this and look at the memory pointed to by F. If in debug mode you should see:
Code:
CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD FD FD FD FD
That is 20 bytes of uninitialized data followed by 4 bytes for "No Mans Land"
then after the call to delete with NO brackets I see
Code:
DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD
It would appear there is no memory leaks, am I wrong here? (Visual Studio IDE)
even the code:
Code:
class Test
{
int f;
int p;
Test(){};
~Test(){};
}
int main()
{
Test *n = new Test[5];
}
The compiler is simply calling Malloc(44)... so why wouldn't one be able to just free that 44 bytes of memory with delete n