Welcome to MSDN Blogs Sign in | Join | Help
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.

Posted: Wednesday, November 28, 2007 5:46 AM by Chris Becker
Filed under:

Comments

Ben said:

This type of bug would not have occurred if fValid was made const. The compiler would have insisted that it be assigned in the initializer list. One of the constructors would become...

Storage( int x, int y ) : valx(x), valy(y), fValid(x != 0 && y != 0) { }

And the other would be something similar, depending on your intention.

It's too bad that C++ does not have C#'s readonly or Java's final keywords.

Also, FGetValues needs a return value as it is not a constructor.

# November 28, 2007 2:32 AM

doug said:

what is its talking about i was looking up moon on ask and i got here?

# November 28, 2007 9:11 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker