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.
delete is used for one single pointer and delete[] is used for deleting an array through a pointer.
To delete a dynamic pointer array of free store, use the operator, delete [] arrayName, in the same scope. The array delete operator, can have a second and/or third argument.
You will get undefined behavior. Save this answer.
The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).
No, it is undefined to pass any address to delete
which was not returned by new
.
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 operator new(std::size_t)
or operator new(std::size_t, const std::nothrow_-t&)
in the standard library, and the value supplied to operator delete[](void*)
in the standard library shall be one of the values returned by a previous invocation of either operator new[](std::size_t)
or
operator new[](std::size_t, const std::nothrow_t&)
in the standard library.
No, not legal. You can only delete
what you got back from new
, and the exact same applies to new[]
and delete[]
No it is not. You must call delete[] on the very same address (or pointer) that you received from new[]. You might just get lucky that it does not crash, but it definitely does not clear the memory appropriately.
References :
From http://www.cplusplus.com/doc/tutorial/dynamic/
The value passed as argument to delete must be either a pointer to a memory block
previously allocated with new, or a null pointer (in the case of a null pointer,
delete produces no effect).
From http://msdn.microsoft.com/en-us/library/h6227113.aspx
Using delete on a pointer to an object not allocated with new gives
unpredictable results. You can, however, use delete on a pointer with the
value 0. This provision means that, when new returns 0 on failure, deleting
the result of a failed new operation is harmless.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With