Thursday, November 22, 2007

Memory Leak Continued

There was some confusion with regard to my last blog about leaking memory. Suppose the ui_mywidget.h files looks like this:
class Ui_Widget
{
public:
QGridLayout *gridLayout;
QGroupBox *groupBox;
QGridLayout *gridLayout1;
QListWidget *listWidget;
QSpacerItem *spacerItem;
QPushButton *pushButton;

void setupUi(QWidget *Widget);
void retranslateUi(QWidget *Widget);
};
Of course, those 6 QObject derived classes are deleted. But the sizeof(Ui_Widget) = 6 * sizeof(void*) = 24 bytes are not deleted. As Ui_Widget is not QObject derived those 24 bytes leak. Confirmed by valgrind.

In a comment to my last blog Paolo suggested to use auto_ptr or scoped_ptr, which is more elegant than an extra wrapper class :)

4 comments:

Thomas said...

private:
Ui::Foo widget;

which is faster (mallocs are slow!!) and avoids this whole problem.

dhaumann said...

True. All arguments only hold if you want to use forward declarations in the header file to speed up compilation / keep the header files as small as possible.

dhaumann said...

I should also mention that I brought this issue up because it's done wrong lots of times: In KDevelop, in kdepim and lots of other places.

Maybe a krazy check could find such errors... somehow...

Benjamin Meyer said...

Or even subclass it, then you don't have to go ui.widget->, but can just go widget->

class Foo : public QWidget, public Qi::Foo {

}