delete[] with different type undefined behaviour?

  • A+
Category:Languages

I am wondering if this is undefined behavior:

#include <stdint.h>  int main() {   auto* p = new uint8_t[32];   float* c = reinterpret_cast<float*>(p);   delete[] c; } 

In the standard there is

If not, the behavior is undefined. In the second alternative (delete array), the value of the operand of delete may be a null pointer value or a pointer value that resulted from a previous array new-expression.79 If not, the behavior is undefined. [ Note: this means that the syntax of the delete-expression must match the type of the object allocated by new, not the syntax of the new-expression. — end note ]

So interpreting the somewhat unclear phrase

this means that the syntax of the delete-expression must match the type of the object allocated by new, not the syntax of the new-expression

I can say the above is Undefined Behavior, correct?

 


Yes, the behaviour is undefined.

Unless related by polymorphism, the pointer passed to delete[] must be the same type as the one you get back from new[]. (The same applies to delete and new.)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: