Wednesday, January 14, 2009

Static is good, and static is great, but static initialization order sucks. I have had problems that could be attributed to static initialization in c++ before, but I wasn't entirely certain at the time that this was the problem. Just like an ugly memory bug, the static initialization order rears its head with meaningless memory access violations--which in my case seem to always end up deep in the stl. While porting something from linux to Mac, a simple re-ordering of the object files on the make line was enough to solve the problem. Wrapping the static variables in static functions to ensure an initialization order is clearly a better solution.

Obviously these things should become a problem and cause problems before main is even entered. I was also building the application for the iPhone and was experiencing problems with it as well. The problem was a segfault of sorts, and the stack was getting f'ed, and GDB was being almost hopeless. Of course, as I just had problems with static initialization I attributed these problems to be that beast. After several failed attempts at re-organizing the static initialization, digging through the semi-automatic resource handling code--I eventually followed the trail down the wormhole with the debugger to a buffer underflow error. Damn it! The only part of code that was different between the Linux/Mac version and the iPhone version was the loading of resources--which first have to dereferencee file names from the main application bundle. This code was different, and in the iPhone port I was using CFString and its reverse search to find the last occurrence of the '.' for file extensions. Obviously I wasn't checking to see if the return value was within bounds before computing a substring--which suprisingly wasn't being checked in the CFString substring functions. I'm certain I spent an hour looking for that. So obvious, but I was led astray by the static initialization. Cut again by Occam's---again and again and again.

No comments: