0

I'm developing a simple prototype with qt creator.

I have used designer in order to design my windows.

Say us that main window has a menu with an option called "Suspend". When this option is selected, it is called the method MainWindow::on_actionSuspend_triggered() whose simplified implementation could be resumed as follows:

void MainWindow::on_actionSuspend_triggered()
{
  SuspendDialog suspend_dialog(this);
  suspend_dialog.setModal(true);
  auto status = suspend_dialog.exec();
  return;
}

The SuspendDialog was specified with designer, it is derived from QDialog class and it is very simple (three push buttons a combo box and a spin box. This class does not allocate memory.

Now, when I run valgrind inside qtcreator for checking memory usage I get two issues of type Mismatched free() / delete / delete []. Some bizarrus is that the two issues refers the same line, which is at the end of destructor of SuspendDialog whose implementation is:

SuspendDialog::~SuspendDialog()
{
  delete ui;
}

And that was automatically generated by qt designer.

My question is: is this a false positive of valgrind or am I doing some wrong?

Thanks in advance

lrleon
  • 2,610
  • 3
  • 25
  • 38
  • The task has nothing to do with the most of tags but Qt. I also thought I can fix the text but then decided not to: too much. – Alexander V Apr 19 '16 at 06:56

1 Answers1

1

By doing the below you are asking for trouble:

SuspendDialog suspend_dialog(this); // wrong! do not pass 'this' here

Passing pointer to 'this' in Qt implies that you pass the parent responsible for release of that widget. Or, the release will happen twice: first when the object on stack getting destroyed and next when the parent object getting destroyed.

If you execute the dialog with exec() you can still allocate the dialog widget on stack but do not pass this to it:

  SuspendDialog suspend_dialog;
  //
  suspend_dialog.exec(); // exec() only

Or you can allocate the dialog widget in the heap and then you can pass this to it:

  SuspendDialog* pSuspendDialog = new SuspendDialog(this);
  //
  pSuspendDialog->exec(); // or maybe show() depending on task
Alexander V
  • 8,351
  • 4
  • 38
  • 47
  • First of all: thanks for your answer!. I tried with your first way and this causes a crash. Apparently, when the dialog is closed the main window is closed. Maybe is important to note that the application is multi-thread. At the contrary, with the second way (using `new`), that works perfectly and the valgrind issue are not shown more. I'am curious for understanding why the first way does not work. I'am voting your question and I think I will mark it as accepted answer. But I will wait a little while for other responses – lrleon Apr 19 '16 at 13:56