Access Violation on Pointer Delete

Started by
5 comments, last by Fl00Fy 11 years, 1 month ago

Well I'm working on a small project, a Blackjack game in C++. I'm getting an Access Violation error when I try to delete a pointer to an object.


Sprite* message;


void showMessage ()
{
	message->draw();
	glutSwapBuffers();
	Sleep(2000);
	delete message;
}

showMessage() is only called from the function below.


void drawAll()
{
	showHands();
	showButtons();
	if (message != NULL)
	{
		showMessage();
	}
	glutSwapBuffers();
}

I have a feeling it's really stupid problem that I'll probably kick myself over when I found out what it is, but I can't, for the life of me, think of what it is.

I think that's all the necessary code

Any help would be appreciated.

It might be worth mentioning that drawAll() is called in the glutDisplayFunc... But I'm not sure if this would make any difference.

Thanks

Advertisement
How are you allocating message?

Ah yes. Sorry.


void initMessage (char* fileName)
{
	message = new AniSprite (100, 260, fileName, 1, 1);
}

void evaluateEndGameHandsWithMessage (int playerHandValue, int dealerHandValue)
{
	if (isPlayerWinner(playerHandValue, dealerHandValue))
	{
		if (isHandBlackJack(hand))
		{
			initMessage ("BlackJackMessage.bmp");
			drawAll();
		}
		else if (isHandFiveCardTricked(hand))
		{
			initMessage ("FiveCardMessage.bmp");
			drawAll();
		}
		initMessage ("WinMessage.bmp");
		drawAll();
	}
	else
	{
		initMessage ("LoseMessage.bmp");
		drawAll();
	}
}

Any other general advice on the code would also always be appreciated.

Well, looking at it, at least one problem is that you don't set message to null after deleting it. The next time drawAll() is called without an intervening initMessage(), it tries to draw and delete an already deleted message.

Ah I see. I should brush up on my pointers. I assumed deleting it would set it to NULL.
Thanks so much for the help. It solved the problem.

You should also initialize the pointer to NULL. Pointers aren't NULL by default.

In general you need to initialize all your variables (they aren't defaulted on their own in release mode), otherwise they can create hard to track down bugs (especially in networked games).

Alright. Thanks so much.

This topic is closed to new replies.

Advertisement