Sign in to follow this  
Fl00Fy

Access Violation on Pointer Delete

Recommended Posts

Fl00Fy    198

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

Share this post


Link to post
Share on other sites
Fl00Fy    198

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. 

Share this post


Link to post
Share on other sites
SiCrane    11839
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.

Share this post


Link to post
Share on other sites
Fl00Fy    198

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.

Share this post


Link to post
Share on other sites
cardinal    908
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).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this