Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free the memory using delete[] operator on void pointer [duplicate]

Can we free the array of primitive data types by using delete[] operator on void*. Ex.

char* charPtr = new char[100]
void* voidPtr = (void*)charPtr;
delete[] voidPtr;

Or it can be freed by using delete operator like

delete voidPtr

I do not expect it to call the destructor. I only expect it to free the memory whichever is allocated by new operator.

like image 540
Ravindra12jan Avatar asked Dec 29 '25 17:12

Ravindra12jan


1 Answers

No this is not valid, it is undefined behavior if we look at the C++ draft standard 5.3.5 Delete says (emphasis mine going forward):

The operand shall be of pointer to object type or of class type. If of class type, the operand is contextually implicitly converted (Clause 4) to a pointer to object type. The delete-expression’s result has type void.78

and footnote 78 says:

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

On the other hand free does allow you to use a void* but the allocation had to have been via malloc, calloc or realloc.

like image 92
Shafik Yaghmour Avatar answered Dec 31 '25 09:12

Shafik Yaghmour