Qt memory management. What's wrong?
-
Hello everyone!
I have a question about memory leaks in Qt.
I have a QMainWindow with 2 QPushButtons.
First button click signal:
@m_label = new QLabel(this);
QPixmap pix(this->size());
QPainter painter;
painter.begin(&pix);painter.drawPixmap(this->rect(), QPixmap("1.png"));
m_label->setPixmap(pix);painter.end();@
Secont button click signal:
@delete m_label;@
When I start my test application the allocated memory is about 11900 Kb When I click on first button then allocated memory for app is about 12450 Kb When I click on the second button I got allocated memory about 12250 KbWhy I didn't get the same 11900 Kb? Is this a leak?
So if to write the following code:
@QImage img("1.png");
QImage img1("1.png");
QImage img2("1.png");
QImage img3("1.png");
QImage img4("1.png");
QImage img5("1.png");
QImage img6("1.png");
QImage img7("1.png");
QImage img8("1.png");
QImage img9("1.png");@
Then allocated memory grows but doesn't decrease. Why? How to clean this memory leak? -
How do you check memory used by process? Via Windows task manager? If yes than you should avoid it because it can show only rude values and it cannot be used to detect memory leeks.
-
Use properly apps, such as valgrind, to detect memory leeks. Common tools, such as top, are not very good to detect leeks.
-
Yes, danilocesar is right about valgrind (memcheck tool).
-
@m_label = new QLabel(this);@
What that does, is creates a new QLabel, stores the address of the newly created label in m_label -- and the (this) argument registers it with the parent object -- so that when the parent gets deleted -- it'll delete its children (i.e. the label). So the normal Qt style is to not manually delete it, but reuse the label -- and when the containing widget is deleted, it'll automagically delete the children.
Also, be very careful (i.e. don't do it) deleting shit (like the label) in events (like the key-press) cause other than the fact you can get weird problems (use deleteLater to get rid of those) -- but double deleting will probably cause your application to crash.
@QImage img("1.png");
QImage img1("1.png");
...@This is just creating a bunch of Objects on the "stack", they'll get deleted when the stack goes out of scope e.g. the next }
-
I've tried symbian apps (as hooklogger) for that, but I've gave up after some days of usage...
Now, I'm using only valgrind and electricfence (and testing it under linux environment), and avoiding to use symbian's specific code.The result has been pretty satisfactory.
-
But isn't it annoying to run the memory leaks tool in a different environment than Symbian to find leaks. There could cases where there could be a mix of Symbian and Qt code. What happens in that case. For that matter it applies to the other platforms also. How will this issue be addressed?