Is it true that the following yields undefined behavior:
void * something = NULL;
char * buffer = new char[10];
something = buffer;
buffer = NULL;
delete [] something; // undefined??
Do I first need to cast something
to char *
?
Yes, strictly when you use delete[]
the static type of the pointer that you delete[]
must match the type of the array that you originally allocated or you get undefined behaviour.
Typically, in many implementations, delete[]
called on a void*
which is actually an array of a type that has no non-trivial destructor works, but it's not guaranteed.
delete[] buffer
or
delete[] (char*)something
would both be valid.