2007-02-01

 

What's wrong with this code?

Here's a short function:
inline int SecondsToEnergy( float time )
{
return FastFloorfToInt( time * (float)(1 << kEnergyFixedPoint) );
}
It's used in the particle system, and converts particle lifetime to an internal fixed point representation (10 bits for fractional part, i.e. kEnergyFixedPoint=10).

Some of the emitted particles are okay on a Mac, but completely not visible on Windows. This function is to blame.

Of course, what's wrong is the possible overflow in float-to-int conversion. Whenever someone tries to use lifetime longer than about 2097151, the conversion to signed 32 bit integer is undefined. It seems to clamp result in gcc and produce something like -1 in msvc.

Using multiple compilers can be hard, but it can also help in finding obscure bugs. Ha!

Comments
Writing tests helps if you're doing hacks like this ;)


Mav.
 
Well, for a test to catch this it requires the programmer to "see" that overflow is possible. Now, if a programmer sees that an overflow is possible he can write code that deals with it directly, right?

...and I don't see how it's a hack. It converts float to fixed point, that's it.
 
> Well, for a test to catch this it requires the
> programmer to "see" that overflow is
> possible.

Exactly! It seems to be a common misconception nowadays - to assume that unit tests will help to _identify_ bugs.

But unit tests is just a way of regression testing, which insures that known bugs (encountered with this specific code or from general prior experience) will not be introduced during development/refactoring.

(just in case of a flame) ... and I _do_ think that unit tests is a useful tool in developement :)
 
In this case, units tests might have helped - you write tests for common scenarios and for extreme cases (by habit). So when you write a test for a function which deals with number conversion and start looking for a corner case - you start thinking about overflows.
One of the major gains for me was that writing tests makes you think about scenarios when code fails, and kind-of forces to question every line of code. But yes, it does not prevent you from writing buggy code.

Yvl.
 
Post a Comment

<< Home