Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for void pointer in C++ before deleting

I have an array in C++:

Player ** playerArray;

which is initialized in the constructor of the class it is in.

In the destructor I have:

delete playerArray;

except when testing the program through Valgrind it says that there are some calls to delete to a void pointer:

 operator delete(void*)

I want to test whether the playerArray is a void pointer before calling delete to avoid this error.

Does anyone know how to do this?

like image 254
tree-hacker Avatar asked Feb 27 '23 03:02

tree-hacker


2 Answers

Perhaps you meant delete [] playerArray. You need the [] if the pointer is an array, not a single instance.

like image 166
Alexander Rafferty Avatar answered Mar 05 '23 17:03

Alexander Rafferty


Here's how operator delete is defined.

void operator delete(void*) throw();
void operator delete[](void*) throw();

'operator delete' takes a 'void *' since a pointer to any object can be converted to 'void *'.

Note that a void is an incomplete type and hence it is not allowed to delete a void * i.e

char *p = new char;
void *pv = p;
delete pv;            // not allowed

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

In the case where playerarray is a pointer to an array of Players, you most likely want to do it differently. delete pplayer does not do what you want it to.

like image 21
Chubsdad Avatar answered Mar 05 '23 18:03

Chubsdad