2009

Three lines that computed the wrong answer: a bug in the compiler

We wrote a program in C++, and it worked incorrectly. It didn’t crash or hang — it just produced a mathematically wrong result.

I called my colleagues over and we started digging. We checked everything line by line — every line was correct, and the result was still wrong.

So we started simplifying. We removed a class — still wrong. We removed the extra files — still wrong. We threw out everything we didn’t need, and every time the result stayed wrong. In the end the program shrank to literally three or four lines. And even those computed the wrong answer.

There was nothing left to look at in the source, so we disassembled it and read the assembly. And we saw it: right at that spot the compiler had mixed up registers — it wrote the value into one register and read it from another. The bug wasn’t in our code but in Microsoft Visual C++.

We filed a bug report with Microsoft.

What I took from it: when everything checks out and the result still doesn’t add up, cut the program down to the smallest example that still breaks. Usually you find your own bug along the way. But if three lines are left and the program still lies, it’s time to look one level down — at the assembly. Only then can you believe it’s the compiler’s fault.