c++allocation

allocate as std::byte[10], deallocate as short*


I come to C and C++ from Assembly before 2.5 decades.

I inherited some things implied in assembly, to both C and C++, but later I realized that these things are actually undefined behavior.

One of these was the difference between delete ptr and delete[] array which for OS is usually one call because there are no destructors.

My latest assumption is the following code:

std::byte *a = new std::byte[10];
short *b = reinterpret_cast<short*>(a);
delete[] b;

Is this undefined behavior? There are no destructors at all.


Solution

  • Yes, it is undefined behavior. The type given to the delete[] expression must be similar to the actual type of the object it refers to.

    "similar" means essentially that it can only differ in const-qualifications.

    Similarly doing almost anything else with b (except casting it back to std::byte*) will have undefined behavior. This kind of reinterpret_cast will usually end in undefined behavior. There are only a few very specific use cases that are well-defined.

    In C++, contrary to assembly, there is an object model and you need to think in terms of these objects which hold values specific to their type, not in terms of memory locations that hold untyped bits which can be interpreted as any type for any operation.