views:

713

answers:

4

I am building a Qt 4.5 application on Windows using Visual Studio 2008. Whenever I run my application in Debug mode and then close it, Visual Studio prints the following to the output pane:

Detected memory leaks!
Dumping objects ->
{696512} normal block at 0x01981AB0, 24 bytes long.
Data: < > 00 CD CD CD 00 00 00 00 00 00 00 00 00 00 00 00
{696511} normal block at 0x02E59B70, 12 bytes long.
Data: < U2g U2g> B0 1A 98 01 E8 55 32 67 E8 55 32 67

And the output reports hundreds of such blocks. I have noticed this particularly when using Qt 4's Model/View framework. Does Qt in fact have memory leaks, or are there circumstances under which Visual Studio misreports leaks?

+1  A: 

Make sure you're using dynamic memory in Qt-way, e.g.

#include <QObject>
#include <QString>

class MyClass : public QObject
{
public: 
MyClass (const QString& text, QObject *parent = 0);
...
};


int main()
{
QObject parent;
MyClass *a;
a = new MyClass ("foo", &parent);
...
}

(c) Johan Thelin, "Foundations of Qt Development"

MadH
@MadH: Yes, I have properly parented all Qt objects as you mentioned. For classes that don't inherit QObject, I use Boost smart pointers. So I have only a handful of objects whose memory I'm managing myself.
Krsna
@Krsna then it would be interesting to know the answer ;-)
MadH
+1  A: 

The memory leak info is provided by the debug windows runtime. Your program can interact and configure this.

The number in braces {696512} is the allocation order number. If this number is always the same, then you can set a break point on this allocation by passing the number to _CrtSetBreakAlloc. Run the program in the debugger again and the debugger will stop when the leaked memory is allocated.

Call this function early in main. If the number is not always the same, try to reproduce the memory leak with reduced code until it is always the same.

For more information see Memory Leak Detection Enabling

iain
A: 

I had a chance to profile my project using DevPartner. The surprising thing is that it reports memory leaks in QtGuid4.dll and QtCored4.dll; however, after manually looking at each case, I discovered that they were all false positives.

As a side note, there were no memory leaks reported in the code using Qt.

Krsna
A: 

I think this happens when the memory leak detector is checking for leaks before QT does it's cleanup. I fixed this problem by moving my qtmaind.lib, QtCored4.lib, QtGuid4.lib, QtOpenGLd4.lib, etc to the bottom of the linker dependencies box in VS's project settings dialog.