About Me
Programming. Realtime computer graphics. Demoscene. Game development. Stuff. LinksArchives
Misc |
2007-02-01What's wrong with this code?Here's a short function: inline int SecondsToEnergy( float time )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
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.
Post a Comment
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. << Home |