Tuesday, April 29, 2008

C++ stack overflow

While searching for infinity and indeterminate in C++ a few days ago I came across a bizzare bug report that left me shievering and made me feel so powerless. Ironically it was a case where the power function (pow) was used, Pow function not working:

"When C++ compiler is compiling a function that returns double, it pushes the return value on the coprocessor stack (i.e. on ST0). If the caller ignored the return value, the compiler generates the instructions that free the stack of the coprocessor. But if we casted the function pointer to a void-returning function, the caller won’t free the coprocessor and therefore it will stack-overflow after a while."

I wrote something similar to the code mentioned in the above page:


As you can see, we made an error by casting a double returning function to a void pointer. But since that seemingly has nothing to do with the rest, everything should be fine and the code should not enter the "if (dValue != 100)" block. The output tells a different story:


Notice that after iteration 7, although dValue is 100 upto 17 digits, it still enters the "if (dvalue != 100)" condition. Interestingly, the assertion does not fail (which should, if it enters != 100)! But if you put the assertion just after line 22, the assertion will fail! For the reason of this strange bug, read the link above.

Now, how on Earth can you trace the origin of such a case in a large program? You need to disassemble the shit out of it! Everyday the evidence whispers to me that C++ should be avoided whenever possible. Especially if you are not a software engineer, but rather use software as a tool to explore physical phenomena (like me). ADA comes to mind, if only it had a cool IDE. Could C# be a second best to realize defensive programming? Or may be I should never write large software and be content with my toy programs ;)

Quote of the day:

"Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?" -- Brian Kernighan, "The Elements of Programming Style", 2nd edition

No comments: