Deleting void pointers

Started by
3 comments, last by Fruny 19 years, 2 months ago
Is it safe to delete a void pointer without casting it to its base type? Will it always delete the right amount of memory? Assume that I never allocate arrays, only single objects. For example:


enum DataType
{
	DATA_INT,
	DATA_STRING
};

class GameMessage
{
public:
	GameMessage( DataType Type, void* pData )
	{
		switch( Type )
		{
		case DATA_INT:
			m_pData = new int;
			*(int*)m_pData = *(int*)pData;
			break;

		case DATA_STRING:
			m_pData = new std::string;
			*(std::string*)m_pData = *(std::string*)pData;
			break;
		}
		m_DataType = Type;
	}

	~GameMessage()
	{
		delete m_pData;		// Is this correct?
	
		// Or maybe I should do:
		switch( m_DataType )
		{
		case DATA_INT:
			delete (int*)m_pData;
			break;
		case DATA_STRING:
			delete (std::string*)m_pData;
			break;
		}
	}

	void* m_pData;
	DataType m_DataType;
};



Advertisement
Your example should work, memory is allocated by blocks
(look the malloc and free functions, they use void* )
------------------"Between the time when the oceans drank Atlantis and the rise of the sons of Arius there was an age undreamed of..."
No! new and delete are different to malloc and free because they call constructors and destructors. If you delete a pointer to a non-POD type via a void * the destructor will not be called! Don't circumvent the type system. Use something like boost::variant if you really need differing data types or rethink your design.

Enigma
deleting a void pointer is bad, as it won't know what deconstructor to invoke. Using free is also bad; never mix new/free or malloc/delete. If you must, cast it to the correct type and delete that.
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other player's eyes with his King.
Quote:Original post by Arcibald Wearlot
Is it safe to delete a void pointer without casting it to its base type? Will it always delete the right amount of memory?


No. It's not safe. It has undefined behaviour. Which means that compiler writers are allowed to assume you will never do that. They don't have to test for that case, don't have to flag it as an error.

... a bit when people write IO routines that expect a number and somebody comes in and types text ...
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement