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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.