I have:
int *ptr = new int[8];
delete[] ptr; // it ok, all ptr is delete;
but if I have:
int *ptr = new int[8];
ptr++;
delete[] ptr;
My question:
Does delete[]
delete all ptr
from ptr[0]
to ptr[7]
or just from ptr[1]
to ptr[7]
?
And, if it deletes from ptr[1]
to ptr[7]
, how does delete[]
know the real size to delete this time?
Yes, it destroys the object by calling its destructor. It also deallocates the memory that new allocated to store the object. Or does it only destory the pointer? It does nothing to the pointer.
If delete is applied to one of the pointers, then the object's memory is returned to the free store. If we subsequently delete the second pointer, then the free store may be corrupted.
Neither; it's undefined behaviour, which usually means it'll crash the program.
The pointer you pass to delete[]
must be one that was previously returned from new[]
. No exceptions*. new[]
returned a pointer to the first element of the array, so you must pass a pointer to the first element of the array to delete[]
.
* the only exception is that you can pass a NULL pointer, in which case it will do nothing.
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