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

Author Topic: I fixed an issue that caused a crash at the end of the program using TGUI librar  (Read 955 times)

0 Members and 1 Guest are viewing this topic.

hdsiria

  • Newbie
  • *
  • Posts: 23
    • View Profile
I fixed an issue that caused a crash at the end of the program using TGUI libraries.
The reason is a flaw in the code design
I built a game state machine, and different game state classes.
Each game state class has a tgui object and draws it
When I created a tgui::button for the GameStatusGaming state, the program ran fine, but when I closed the program, it crashed in vs debug mode

I've tried many versions of tgui with this problem, so it's not a problem with tgui per se
I finally found that these game state classes were not released in my state machine destructor, which is what caused the tgui to crash.
I released them in the destructor of the state machine
        virtual ~GameStatusMachine(){
                //Destruction status class
                for(const auto &status:m_statusList){
                        delete status;
                }
        }
 
But it crashed again after the program ended
I set a breakpoint at the destructor and I see that there's no breakpoint running,This means that the state machine is not destroyed after the program ends
I checked the main function, it created a new game window class, and it didn't get released after the function ended
        GameWindow *window;
        try{
                window = new GameWindow;
        }
        catch(const char *e){
                std::cerr<<e<<"\n";
                return -1;
        }
        window->show();
        return 0;
 

So these status classes and TGUIs are not destroyed after the main function ends, they are still running, waiting for the system to release them.tgui components are still trying to draw,So it leads to a crash
I manually released the game window class,
        delete window;
        return 0;
 
I ran again without crashing at the end

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11030
    • View Profile
    • development blog
    • Email
You can avoid such issues by relying on RAII (Resource Allocation is Initialization) by using smart pointers such as std::unique_ptr and never doing manual memory management (new / delete).
That way you can ensure that once the smart pointers run out of scope, the referenced object is deleted.

In "modern" C++ you should never really call new and delete directly.

As for TGUI, I don't know how it's managed, but it might run into Static Initialization Order Fiasco.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/