The Phase of the Moon [Bug]
Here’s a bug I came across that earns the “phase of the moon prize”. See if you can pick it up:
class Storage
{
public:
Storage() : valx(0), valy(0)
{
}
Storage( int x, int y ) : valx(x), valy(y)
{
fValid = x != 0 && y != 0;
}
FGetValues( int& x, int& y )
{
if( fValid )
{
x = valx;
y = valy;
return true;
}
return false;
}
private:
int valx;
int valy;
bool fValid;
};
See it? Neither did I for a while. Until someone found that everyonce in a while, we’d return 0’s for valx and valy. “That shouldn’t happen!” I thought.
The problem of course, is that fValid isn’t initialized in all the constructors, so if you called that specific constructor and then the phase of the moon is right (aka the memory located where fValid is is still set to 1), you’d get incorrect behavior.
The key to debugging this was finding out where the value fValid came from. I started at the constructors and noted it wasn’t passed in. Then I traced through where it was used to see if it was modified anywhere, the only place being the constructors. Since it can’t be change anywhere else, it's very likely an initialization problem.