Friday, May 8, 2009

Interesting Bug in C++ code

I was trying hard to release a 1.0 version of Adrian game, but we had to face a showstopper bug which was crashing the Windows Release version, on start of the game itself. After hunting for it for a long time, I was able to figure out the bug, which turned out to be a very interesting issue.

Basically we have a structure which has an embedded vector STL class in it. What the code was doing was to create the structure, and before assigning contents to it, was simply memsetting the entire structure to 0. While this is normal operation in any C code, in C++ this can cause very weird bugs.

When the vector is embedded in the structure as a C++ class (Composition), it's constructor gets calls when the structure is created. This constructor actually setting some fields (pointers namely) to some initial values. However, when we memset the structure, the vector fields are again initialized to zero (and the pointer to NULL). So whenever I try to access the vector it causes a panic.

The fix was to simply remove the memset code, and then write a new constructor for the structure, which will initialize the other variables to zero, leaving the vectors alone. What a bug! it took a lot of hunting to get to this one :)

Now, We would be able to release Adrian 1.0 version soon.

No comments: