SFML community forums

Help => General => Topic started by: ppsychrite on October 08, 2016, 12:13:45 am

Title: Deleting RectangleShape pointer crashes window?
Post by: ppsychrite on October 08, 2016, 12:13:45 am
Hello!
I'm starting to get into the feel of using pointers and attempted making a RectangleShape using them.
It worked, I was able to make it be displayed, but when I tried deleting it with a Keyboard event the Window proceeded to crash with "has stopped working"
Any reason this is happening and how to fix it?

int main() {
        RenderWindow window(VideoMode(800,600), "Game");
        window.setFramerateLimit(60);


        RectangleShape * Obj1 = new RectangleShape(Vector2f(40, 40));
       

        while (window.isOpen()) {

                Event event;
                while (window.pollEvent(event)) {
                        switch (event.type) {
                                case Event::Closed:
                                        window.close();

                                case Event::KeyPressed:
                                        if (Keyboard::isKeyPressed(Keyboard::Escape))
                                                window.close();

                                        else if (Keyboard::isKeyPressed(Keyboard::W))
                                                delete Obj1;

                        }

                }
                window.clear(Color::Red);
                window.draw(*Obj1);
                window.display();
               
        }
        return 0;
}

 
Title: Re: Deleting RectangleShape pointer crashes window?
Post by: TCVM on October 08, 2016, 02:19:58 am
You are deleting the object, but you are still drawing it to the window after it gets deleted. This causes undefined behavior, and crashes the program.
Title: AW: Deleting RectangleShape pointer crashes window?
Post by: eXpl0it3r on October 08, 2016, 02:37:59 am
Also I hope you are aware that it makes no sense in your code to dynamically allocate the shape. A stack variable will do just fine.
And finally, don't do manual memory management anymore. We have smart pointers now, so we should never have to write new and delete anymore.

(https://bulldozer00.files.wordpress.com/2016/10/leakfree.png)