| 1001010.com |
one zero zero one zero one zero dot com |
...the first example reads...
#include <qapplication.h>
#include <qlabel.h>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QLabel *label = new QLabel("Hello Qt!", 0);
app.setMainWidget(label);
label->show();
return app.exec();
}
Book in question C++ GUI Programming with Qt 3
It's been a while since I played with Qt by Trolltech so I needed a refresher to read. What I got contained code samples that, well reminded me of some unique code I once maintained by some guys after they sold their codebase to GameSpy :-|
Can you spot the red flag that this and all other examples in the first few chapters share?
Here's a tip - the ommission turns my stomach. No, that's too vague.
What if I update the code a wee bit? MS provides a helpfull diagnostic toolset for tracking memory allocations. Let's add it in and see what happens.
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <qapplication.h>
#include <qlabel.h>
int main(int argc, char *argv[])
{
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
QApplication app(argc, argv);
QLabel *label = new QLabel("Hello Qt!", 0);
app.setMainWidget(label);
label->show();
return app.exec();
}
Lo and behold, what informational goodies have been bestowed upon us through the debug out window....
Detected memory leaks!
Dumping objects ->
C:\Program Files\Microsoft Visual Studio\VC98\INCLUDE\crtdbg.h(552) :
{52} normal block at 0x00994328, 184 bytes long.
Data: <HP@ > 48 50 40 00 E2 CD CD CD 00 00 00 00 00 00 00 00
Object dump complete.
As you might have guessed, we're new'ing memory, but we're never delete'ing it.
I hate it when programming books teach bad habits.
How do we fix it? Just add a delete
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <qapplication.h>
#include <qlabel.h>
int main(int argc, char *argv[])
{
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
QApplication app(argc, argv);
QLabel *label = new QLabel("Hello Qt!", 0);
app.setMainWidget(label);
label->show();
int nResult = app.exec();
delete label;
return nResult;
}
TaDa! No more leaks.
It would have been nice if this wasn't the only book on Qt at my not so local B&N - the two nearby Borders had nothing comming close to Qt on the shelves :(
All in all, it's a great refresher - I just wish I found a better book. Maybe later I'll head down to Microcenter . They usually have a healthy selection of geek books.
You know, I may just finish the book and treat it as a "where's waldo" of finding bugs ;-)