Tuesday, August 04, 2009

Memory Mis-Management

After cracking open Qt Creator and picking up Qt 4.5 development quite nearly two years after putting it down I found my C/C++ to be really wanting. All the habits I had developed earlier had simply leaked out of my head. I hadn't thought in terms of delete/malloc/free/pointers/references/virtual functions in so long that those neurons had since been re-allocated to other important devices, such as figuring out how to get americanos out quickly without breaking the espresso maker.

My brain just doesn't shift from domain to domain like it used to. Recently I was working on reducing some sort of algebraic expression of matrix transformations or some crap when a visiting fellow asked about normalizing data in an RDBMS. My brain shifted without a clutch. I kinda sat there, utterly stupefied, while my noggin tried desperately to come to terms with a) what words actually meant in the English language and b) how to shove data into a database table.

My brain is currently doing that with C++ memory management, too. Valgrind has very politely brought to my attention that my app is leaking like a freaking waterfall and my pointer management is beyond stupid. I needed a boot to my brain to make it jump back to C++ object-land.

Evidently my brain is not the only one that Java has softened. Not too long ago the Amarok team noticed that an influx of Java programmers brought with it fairly poor memory allocation habits and posted "Tips on memory management with C++ and Qt" to the mailing list. Both the message itself and the following responses I found interesting... they gave a quick synopsis of things that Javabrains do incorrectly when having to think in Qt's C++ garden.

I started reading Appendix B of Mark Summerfield's First Edition of C++ GUI Programming with Qt 4. The appendix, "Introduction to C++ for Java and C# Programmers," skips extraneous lessons concerning object oriented programming and directly addresses the C++ conventions that have since escaped my memory. The language in the book is direct and approachable; now that I'm into it the practice of everything is starting to come back to me now. Hopefully now I won't make stupid inheritance mistakes with virtual functions.

The paradigm of passing by value vs. passing by reference takes breaking some tough habits, but Qt is helping me out. Valgrind telling me of abandoned and undeleted objects finally reminded me why every object in Qt needs a parent - the removal of the parent needs to signal the removal of all children. I also need to be more disciplined in the use of QPointer to pass around references. Just as Crystal Space's smart pointers saved me numerous times in the past I'm sure Qt's smart pointers will save me from myself as well.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.