Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete[] with different type undefined behaviour?

Tags:

c++

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?

like image 278
Gabriel Avatar asked Sep 26 '18 07:09

Gabriel


2 Answers

Yes, the behaviour is undefined.

The pointer passed to delete[] must be the same type as the one you get back from new[].

Note that for delete and new, the pointer submitted to delete is allowed to be related by polymorphism.

like image 112
2 revs Avatar answered Oct 04 '22 16:10

2 revs


Yes, the code in indeed Undefined Behavior. The phrasing means that it would still be UB when you would rewrite it as

int main() {
  void* p;
  {
     using T = uint8_t;
     p = new T [32];
  }
  {
    using T = float;
    T* c = reinterpret_cast<float*>(p);
    delete[] c; // The behaviour is still undefined.
  }
}

IOW, the types really have to match exactly, not just in name.

like image 38
MSalters Avatar answered Oct 04 '22 16:10

MSalters