I’m wondering specifically about the following situation (which I discovered in some code I have to work with):
SomeClass *ar = new SomeClass[2];
ar++;
delete[] ar;
This code seems to be working fine – i.e. not crashing (win32, built with VS2005).
Is this “legal”? It certainly doesn’t feel right.
No, it is undefined to pass any address to
deletewhich was not returned bynew.Here is the quote from the Standard.
§ 3.7.4.2-3
If a deallocation function terminates by throwing an exception, the behavior is undefined. The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. Otherwise, the value supplied
to operator
delete(void*)in the standard library shall be one of the values returned by a previous invocation of either operatornew(std::size_t)oroperator new(std::size_t, const std::nothrow_-t&)in the standard library, and the value supplied to operatordelete[](void*)in the standard library shall be 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.