Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Deleting RectangleShape pointer crashes window?  (Read 1874 times)

0 Members and 1 Guest are viewing this topic.

ppsychrite

  • Newbie
  • *
  • Posts: 6
    • View Profile
Deleting RectangleShape pointer crashes window?
« 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;
}

 

TCVM

  • Newbie
  • *
  • Posts: 30
    • View Profile
Re: Deleting RectangleShape pointer crashes window?
« Reply #1 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.

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11034
    • View Profile
    • development blog
    • Email
AW: Deleting RectangleShape pointer crashes window?
« Reply #2 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.

Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/