Heap-Allocated QApplication Getting Deleted

Viewed 124

In a basic C++ Qt Widgets application, creating a QApplication on the stack or heap-allocating it directly in the main function works, but calling a function the heap-allocates a QApplication and using the returned pointer gives a segmentation fault:

#include <QtWidgets>

QApplication* create_application(int argc, char* argv[]) {
    return new QApplication(argc, argv);
}

int main(int argc, char* argv[]) {
    QApplication* app = create_application(argc, argv);
    QWidget window;
    window.show();
    app->exec();
}

I think it's being automatically delete, but I can't figure out why.

1 Answers

The problem is not that you create your QApplication with dynamic storage duration, but that the constructor of QApplication is QApplication::QApplication(int &argc, char **argv) taking argc as reference.

And these two notes/warnings:

Note: argc and argv might be changed as Qt removes command line arguments that it recognizes.

Warning: The data referred to by argc and argv must stay valid for the entire lifetime of the QApplication object. In addition, argc must be greater than zero and argv must contain at least one valid character string.

The reference to the argc parameter in your create_application becomes invalid after you exit that function, which violates that warning.

If you change QApplication* create_application(int argc, char* argv[]) to QApplication* create_application(int &argc, char* argv[]) it will work, as argc now referes to the argc parameter of main and is not a copy of it.

Related