Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why deleting void* is UB rather than compilation error?

Why would deleting an object through void* be undefined behavior, rather than compilation error?

void foo(void* p) {
    delete p;
}

This code compiles and produces code, albeit with the warning on gcc and clang (surprisingly, ICC doesn't give a warning):

:2:5: warning: cannot delete expression with pointer-to-'void' type 'void *' [-Wdelete-incomplete]

Why is not simply malformed program with invalid syntax? Looks like Standard doesn't spend too much time on it, saying in [expr.delete] that

This implies that an object cannot be deleted using a pointer of type void* because void is not an object type.

Would there be any reason I am missing why this does not trigger a hard compilation error?

like image 823
SergeyA Avatar asked Jun 13 '18 17:06

SergeyA


People also ask

Can you delete a void pointer?

It is also called general purpose pointer. It is not safe to delete a void pointer in C/C++ because delete needs to call the destructor of whatever object it's destroying, and it is impossible to do that if it doesn't know the type.

What is delete function C++?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.


1 Answers

In modern C++ deleting a void * pointer is ill-formed (i.e. it is what we typically call a "compilation error")

8.3.5 Delete
1 [...] The operand shall be of pointer to object type or of class type.

void * is not a pointer to object type.

In C++98 the situation was different. Deleting a null pointer of void * type was a NOP, while deleting a non-null pointer of void * type was UB.

This change in the specification appears to have been triggered by defect report #599. The original spec allowed supplying null pointers of any pointer type in delete-expression, like function pointers, for example. This looked unnecessarily permissive. The resolution of DR#599 tightened the requirements, outlawing void * as well.

like image 58
AnT Avatar answered Oct 12 '22 10:10

AnT