Testing void pointer in C ++ before deleting

I have an array in C ++:

Player ** playerArray; 

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

In the destructor, I have:

 delete playerArray; 

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

  operator delete(void*) 

I want to check if playerArray is a void pointer before calling delete to avoid this error.

Does anyone know how to do this?

+4
source share
3 answers

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

+5
source

The definition of the operator is defined here.

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

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

Note that void is an incomplete type and therefore is not allowed to delete void * ie

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

Footnote 78: This means 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 will most likely want to do it differently. delete pplayer does not do what you want.

+3
source

I think the valgrind warning that the deletion occurs in the context of something like this:

 int foo(void *mydata){ { SomeClass some_value = static_cast<SomeClass> mydata; some_value.dosomething(); // now we're done with it delete mydata; } 

although the cast is great, since you know that the void pointer is actually a type, you are still doing something suspicious because you are deleting the void pointer, not the typed pointer. If SomeClass is a POD, perhaps this is normal, but if it has some critical work to do in its destructor, that destructor will never be called.

0
source

All Articles