0

I have a Class Player like this:

class Player
{
    public:
    Player();
    ~Player(void);
    Sprite *sprite;
    Sprite *rocket;

    void draw(int x, int y, SpaceInvaders *system);
}

and in Player.cpp

void Player::draw(int x, int y, SpaceInvaders *system) {

    sprite = system->createSprite("data/player.bmp");
    sprite->draw(x, y);

}

Player::~Player(void)
{
    sprite->destroy();
    rocket->destroy();
}

This draw method is called in a while loop in main:

player.draw(int(xPos), 480-32, system);

The game runs fine until I X the window. That's when I get "Access violation reading location 0x00000004" on the first line in the Player::draw method. I've read that it might be due to passing a null pointer or null reference but I don't know how to fix this.

Would appreciate any help, thanks!

thehindutimes
  • 321
  • 1
  • 6
  • 19
  • 3
    Did you follow [The Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three)? – jrok Aug 22 '13 at 18:50
  • "X" the window? Close the window? Is this running in a Windowed environment (Win32, QT, Gtk) or as a console app? – Chad Aug 22 '13 at 18:50
  • What is the definition of `Player::Player()`? – cdhowie Aug 22 '13 at 18:53
  • 3
    Side Note: That `sprite`, a member variable of `Player`, is reassigned *on each `draw()` invocation* tells me this will ultimately be the least of your worries. If `draw()` lives up to its name you likely have a *raging* memory leak in this code. – WhozCraig Aug 22 '13 at 18:53
  • Just stop passing pointers –  Aug 22 '13 at 18:57
  • Can we see the code for the constructor please. – Len Holgate Aug 22 '13 at 19:03

1 Answers1

0

It's most probably because when closing the window, something gets destroyed while draw is called - most probably the system pointer.

In your case, draw should never be called when the user wants to close its window (unless the x calls another function to start a closing process of some sort). The best would be to first validate that system is not NULL or even better, use a shared pointer to ensure it is still valid when being used. Afterwwards, you shoiuld ensure that draw is not called when the window is closing - that should be done when calling the draw function (or above depending on how you've designed your application.

On a side note, unless you have a caching mechanism (and even that is not the best way to do it), you're recreating your sprite everytime it's being drawn. I suggest you keep a member variable and initialize the sprite in the construtor.

MasterPlanMan
  • 992
  • 7
  • 14