#2225 g++ miscompiles floating-point comparison in the following example

OTHER
unread
nobody
None
Bug
none
Unknown
False
2014-07-07
2014-07-07
Vitezslav
No

Compile the attached file floating-point-test.cpp with optimization enabled (-O1 or -O2) and run it. The program output differs from what you get when it is compiled without optimization.

You would expect strings s1 and s2 to contain the same values after initialization, but when compiled with optimization, they don't.

I can reproduce this with 32-bit version of gcc 4.8.1 (rev5) or even the older 4.7.2 version. However, I can't reproduce it on linux.

The problem seems to be with the code generated. After the call to getLength2, when first comparison occurs, the result of getLength2 is stored in a register in the processor and uses an extended precision format. But after this first comparison the value is stored into memory, truncated to double precision, and is reloaded before the second comparison. But, since the value was truncated, the result of the second comparison is not the same.

1 Attachments

Discussion

  • Keith Marshall
    Keith Marshall
    2014-07-07

    Thanks for the report; unfortunately, there isn't much we can do about it!

    I suspect this is an effect of GCC's well known excess precision bug. Thus, you will need to report it directly to the GCC maintainers themselves, as any resolution must come from them. Good luck convincing them that this needs attention, as they have a long standing reputation for sweeping this one under the carpet.

    The work around, (which I agree is far from ideal), is to always force a store of double precision data to memory, before attempting to use it.