[Solved] Segfault on QApplication exit

  • I've been debugging a segmentation fault that happens when closing a Qt application composed of several projects. We ended up trying this very simple test:

    @#include <QApplication>
    #include <QMainWindow>

    int main(int argc, char *argv[])
    // Method 1: CLOSES CORRECTLY
    /QApplication a(argc, argv);
    QMainWindow w;
    return a.exec();

    // Method 2: CAUSES SEGFAULT
    QApplication *a = new QApplication(argc, argv&#41;;
    QMainWindow *w = new QMainWindow();
    return a->exec&#40;&#41;;


    Project file:

    QT += widgets
    TARGET = test
    TEMPLATE = app
    SOURCES += main.cpp@

    I realized that the first method (commented code), always closes correctly and without errors while the second method which uses pointers causes a segfault on exit. This seems to happen randomly. This behavior appeared after migrating from Qt 4.6 to Qt 5.0.1, on CentOS 6.4.

    Anyone would have an idea why the method using pointers does not work correctly anymore? Is this method valid? Is this behavior normal?

  • With your second method, the objects are allocated on the heap, but you never delete them!

    The memory leak that this causes probably doesn't matter much, as the process is going to exit anyway.

    Nonetheless it's bad practice to not clean up your heap objects properly. So please try:

    QApplication *a = new QApplication(argc, argv);
    QMainWindow *w = new QMainWindow();

    int ret = a->exec(&#41;;
    delete w;
    delete a;
    return ret;


  • Seems like many examples and tutorials I found don't delete objects on the stack declared, probably, as you said, because it doesn't matter in this case. Manually deleting the objects fixed the problem. Still wondering why we didn't notice this before since this is a C/C++ issue and not a Qt one. Anyway, case solved, and I'll stick to good practices. Thanks a lot!

  • Well, you can assume that QApplication and QMainWindow will also allocate system resources, e.g. from the underlying windowing system. If you never destroy these objects, their destructors never get executed and thus they will never get a chance to do a proper clean up, e.g. of system resources. Here things can go wrong!

    BTW: If examples don't delete heap objects, then that's probably because the example code wants to illustrate a specific aspect, but is not intended to be used 1:1 in a real software and thus leaves out various "details".

  • Though this is marked as solved, I can't see the reason for the SEGFAULT when no desctructors are called. Can anyone explain please?

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.