Wednesday, 24 April 2013

Corrupting my Heap

I've had a hell of a few days, the family thing has droned on, but I'm fast washing my hands of the situation - they can go masturbate in their own mess as far as I'm concerned, this makes the wife and I the bad guys, but logic will one day prevail, most likely when my mother can't interrupt people and pontificate utter bollocks in her rude manner.

Anyway, what about this Heap Corruption?  Well, what a debugging session I've just had, it lasted nearly 3 hours - that's a long one for me - especially with my C++ code.  That's not to be big headed, but I have evolved my coding style and used the libraries (boost & std) in the manner I do without issues all the time, so to suddenly find a bug - one corrupting the heap - was a bit of a nasty sting.

I can't go into specifics, due to the nature of the work I was carrying out for my employer, but here's the gist...

A function was bound with boost::bind... And was called back from another location in the code at regular & mutually exclusive intervals, so on a timer... Here's pseudo code:

#include <memory>
#include "TimerFoo.h"

using namespace std;

void baa (const bool& p_Error, const bool& p_Cancelled)
   if ( ! p_Error && !p_Cancelled )

unique_ptr<Timer> l_MyTimer = unique_ptr<Timer>(new Timer(boost::bind(&baa, this, _1, _2)));

Right, and after waiting the 5 seconds the baa function would be called, and suddenly my application would crash horribly, inside the boost libraries.  Either in the function pointer headers, or even in the unique pointer header of the std.  It was an utter mess.

And the call stack gave no clues about the problem, it neither helped workout quite what had run.

The problem turned out to be a problem inside the "DO SOMETHING", which was calling into the psapi and trying to use the TCHAR pointer somewhere incorrectly.  I removed that code and its all fine again - but so scary a crash.

It has spurred me to want to update my personal coding standards and include the rule "If you have a boost::bind bound function, and suddenly your code crashes, rem out that function's body and re-run".  This is essentially how I found the above bug, I removed the whole guts of the callback and voila the code ran, but with the heap corruption it was hard, nigh impossible, to see what had actually gone wrong.

No comments:

Post a Comment