Let's suppose the following code:
int* ptr = new int[10];
...
...
ptr += 2;
delete[] ptr;
ptr = NULL;
Should ptr be pointing on the first element of the array when the delete is called?
Let's suppose the following code:
int* ptr = new int[10];
...
...
ptr += 2;
delete[] ptr;
ptr = NULL;
Should ptr be pointing on the first element of the array when the delete is called?
If you call delete
on something that you didn't get back from new
, that's undefined behavior.
So the result of the following code is undefined:
int* ptr = new int[10];
ptr += 2;
delete[] ptr;
Let's look at the standard as well:
C++ 2011. Section 3.7.4.2 Deallocation functions. Paragraph 3.
Otherwise, the behavior is undefined if the value supplied to
operator delete(void*)
in the standard library is not one of the values returned by a previous invocation of eitheroperator new(std::size_t)
oroperator new(std::size_t, const std::nothrow_t&)
in the standard library, and the behavior is undefined if the value supplied tooperator delete[](void*)
in the standard library is not one of the values returned by a previous invocation of eitheroperator new[](std::size_t)
oroperator new[](std::size_t, const std::nothrow_t&)
in the standard library.