开发者

Undefined behavior on deleting char array trought void *

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 开发者_Python百科char * ?


Yes.

From the Standard (5.3.5 Delete):

The value of the operand of delete shall be the pointer value which resulted from a previous array new-expression.72) 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. ]

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

**This implies that an object cannot be deleted using a pointer of type void* because there are no objects of type void.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜