Delete pointer to C ++ pointer while increasing the 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 is:

Does delete[] all ptr from ptr[0] to ptr[7] or only from ptr[1] to ptr[7] ? And if it deletes from ptr[1] to ptr[7] , how does delete[] know the actual size to delete this time?

+5
source share
1 answer

Neither; this behavior is undefined, which usually means that it will crash the program.

The pointer you pass to delete[] must be the one that was previously returned from new[] . With 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.

+18
source

Source: https://habr.com/ru/post/1236422/


All Articles