Hai Nguyen Hai Nguyen - 3 months ago 9
C++ Question

Delete array pointer c++ when increase pointer?

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:
delete[]
delete all
ptr
from
ptr[0]
to
ptr[7]
or delete from
ptr[1]
to
ptr[7]
?
and if delete from
ptr[1]
to
ptr[7]
, how
delete[]
know real size to delete this time.

Answer

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.

Comments