Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator delete and casting

Tags:

c++

Can i use smth like the following code:

int main()
{
    int* foo = new int;
    double* bar = reinterpret_cast<double*>(foo);
    delete bar;
}

Is it UB?

I think that we need to call operator delete only for pointers returned by operator new, but what about casting in this case?

I think that it's UB since the reinterpret_cast don't give any guarantees about the resulting pointer. Am i right?

Can somebody post the right quote from the standard, please?

like image 271
FrozenHeart Avatar asked Jun 24 '13 11:06

FrozenHeart


2 Answers

§5.3.5/2 "In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (1.8) representing a base class of such an object (Clause 10). If not, the behavior is undefined." Since bar points to a double, it does not point to an object created by a previous new-expression (which created an int).

like image 78
James Kanze Avatar answered Oct 03 '22 13:10

James Kanze


From 5.3.5-3:

In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

Leaving aside possible problems in using reinterpret_cast here, this is UB because the types do not match. Imagine some nontrivial type, then you can easily see this as the "wrong" dtor would be called.

Additionally using the result of reinterpret_cast for anything else than casting it back is mostly unspecified by the standard.

like image 23
PlasmaHH Avatar answered Oct 03 '22 13:10

PlasmaHH