Allegro 5 - Bullet dispose when gets to the border

41 Views Asked by At

Me and a classmate are making an Allegro 5 game, a Defender remake, but we have some problems with the bullets. When the bullet impacts a borderline the game crashes completely.

void Player::render() {
    

    al_map_rgb(0, 0, 0);
    nave = al_load_bitmap("images/naveV2_xs.png");
    

    for (auto& bullet : bullets) {
        bullet->render();
    }

    al_draw_bitmap(nave, x, y, 0);
}

void Player::dispose() {
    for (auto& bullet : bullets) {
        delete bullet;
    }

    bullets.clear();

    al_destroy_event_queue(event_queue);
    al_destroy_bitmap(nave);
    
}
1

There are 1 best solutions below

0
amarillion On

I can't be 100% sure what the problem is, because you only shared a fragment from your code, but I see a few general problems:

In normal use, an allegro event queue would be a global object (used for timers and keyboard input) that is used for the lifetime of the game. If the player event_queue is shared elsewhere in the game, then destroying it in the Player::dispose() method would potentially kill it while it's still in use by the rest of the game, which could lead to the crash you describe.

Also, destroying the nave bitmap in the Player::dispose() method could lead to a crash if you're not careful to make sure that the Player::render() method is no longer called afterwards. If you still call Player::render() after Player::dispose() then you'll see a crash.

I suspect that the player is disposed when reaching the edge of the screen, and then either of the above two problems is causing the crash.

Furthermore al_load_bitmap should be called in the initialization phase of your game, not in the rendering loop. The name of your function Player::render() suggests that it's called every frame of the game. This would mean that you allocate new bitmap memory for each frame, which would mean a memory leak.

As a general piece of advice, you should take a close look at the lifecycle of variables, when they are created, when they are initialized, and when they should be cleaned up. Cleaning up data while it's still in use will lead to a crash like you describe.