Does this Qt code leak memory?

Jim G

I try to learn more about programming by studying open source using UML. The code I have found is in the stage between Qt 3 and Qt 4. The project is not that active so I ask this question here. Maybe I should add that the program using this code do run.

Note, I am a junior. I ask because I want to learn.

My question is simple:
Do this code leak memory?

If not, why ?

  void warn(const QString & s) {

      // not showed dialog to compute needed size

      QDialog d_aux;
      Q3VBoxLayout * vbox_aux = new Q3VBoxLayout(&d_aux);

      vbox_aux->setMargin(5);
      Q3TextEdit * e = new Q3TextEdit(&d_aux);
      e->setText(s);

      // showed dialog

      QDialog * d = new QDialog;

      d->setCaption("My caption");

      Q3VBoxLayout * vbox = new Q3VBoxLayout(d);

      vbox->setMargin(5);

      Q3TextView * t = new Q3TextView(d);
      QFontMetrics fm(QApplication::font());
      int maxw = (MyWindow::get_workspace()->width() * 4) / 5;
      int maxh = (MyWindow::get_workspace()->height() * 4) / 5;
      int he = (e->lines() + 5) * fm.height();

      t->setText(s);
      t->setMinimumSize(maxw, (he > maxh) ? maxh : he);

      vbox->addWidget(t);

      d->show();
  }

Thanks // JG

lpapp

I think you are leaking memory, but it would be simple to verify with a program like valgrind on Linux and so on. Let us see what dynamic memory allocations you do in your function:

  Q3VBoxLayout * vbox_aux = new Q3VBoxLayout(&d_aux);

That is alright because it gets a parent. Let us see the next:

  Q3TextEdit * e = new Q3TextEdit(&d_aux);

That is also alright for the same reason above. Let us see the next:

  QDialog * d = new QDialog;

Here, you problems begin to arise because the dialog does not have a parent. You have several ways of fixing it.

1) Assign a parent, although this might not be ideal in this case as you do not seem to have any parent'ish look in your code for this widget. That is, nothing that could really become the parent of it unlike your Qt application if you are using that. This fix may require some major rework depending on the whole context that you have shown.

2) Use a smart pointer, e.g. QPointer around it, so it will be managed for you automatically. That should have been available at the age of the code you are using. This may also need some code rework depending on more context that you have not provided.

Let us see the next dynamic memory allocation:

  Q3VBoxLayout * vbox = new Q3VBoxLayout(d);

That is alright for the reasons mentioned before. Let us see the next and last:

  Q3TextView * t = new Q3TextView(d);

That is also alright for the reasons mentioned before.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related