The following code creates a window when closing:

#include <QApplication> #include <QTextEdit> #include <QPushButton> #include <QVBoxLayout> int main(int argc, char **argv) { QApplication app(argc, argv); QTextEdit textEdit; QPushButton quitButton("Exit"); QObject::connect(&quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); QVBoxLayout layout; layout.addWidget(&textEdit); layout.addWidget(&quitButton); QWidget window; window.setLayout(&layout); window.show(); return app.exec(); } 

causes the following error: QtCalc(47351,0x7fffce3e73c0) malloc: *** error for object 0x7fff5ea469f0: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug

What is the problem?

    1 answer 1

    The window widget tried to destroy the child widgets and layout as if they were placed in a heap. In fact, everything is placed on the stack, and therefore the standard library stopped this attempt and crashed the application.

    This attempt was caused by the fact that any QObject (of which QWidget is a descendant) undertakes to clean up all child objects behind itself, freeing the author of the program from this duty.

    To solve the problem, you can use the fact that any child QObject sends a signal to the parent when it is destroyed, and it removes the object to be deleted from its list in order to avoid re-deletion.

    That is, if QTextEdit , QPushButton and QVBoxLayout destroyed before QWidget , the latter would not touch already destroyed objects, and the program would end in a normal way. To achieve this effect, simply place the declaration for the QWidget window; before all that will be added to it later:

     // ... int main(int argc, char **argv) { QApplication app(argc, argv); QWidget window; // <--- QTextEdit textEdit; // ... } 

    This will work because local variables (and class members) are always destroyed in the reverse order of the way they were created.