Sunday, August 12, 2007

Objects want to be free - but only be freed once

This weekend wasn't all bad in spite of having both my birthday and wedding anniversary (yes, my wife wanted to make sure i wouldn't forget the latter! ;) as I found the reason for the double-free bug - or at least one of the reasons.




I outlined the collision check loop(s) in an earlier entry. What's not shown in that code snippet is caching of outer loop object type, done to speed up the collision type decision. Even when the outer loop object gets removed in the collision the inner loop still continues afterwards. Check out the picture: the laser bolt colliding with two explosions is the object which gets removed twice. If the outer object type wasn't cached then all remaining collisions with it would be NOPs.

I have at least three ways to fix this:


  1. don't cache the object type

  2. exit the inner loop when outer loop object gets removed

  3. check object type against -1 (free object) every time before freeing one


I will do #2 although it means duplicating some code, as I hate to waste cycles for checking for special cases unless it's absolutely necessary. I will rethink my decision if object removal still bugs.

No comments: