Compiler warning

Ricardo Telichevesky ricardo@teli.org
Thu Jul 31 09:04:00 GMT 2014


Hi,

     Hope this is the right place to ask this question. Is there any way to set -Wxxxx flags to detect the following situation:

     unsigned int x = 1015625426; // a billion

    ....


     size_t numBytes = x * sizeof(double);

... the result is 3830033872 when I should have written instead something like:

        unsigned int x = 1015625426; // a billion

        .....

        size_t numBytes = x;
        numBytes *= sizeof(double);

.. that way the result would be the correct 8125003408. I guess that the precision of any particular operation depends exclusively on its operands, not the left hand side result, the most obvious novice mistake is writing double oneThird =  1/3 => oneThird gets 0. The problem is I have this type of 
situation all over a large code base, and when compiling for 64 bits would be nice to have a warning like:

warning: potential overflow computing numBytes (64-bit) as a product of two 32-bit unsigned integers... or anything that remotely resembles it, so I could find where it might happen in the code. I found the -ftrapv option, would catch the problem at runtime, but I want to fix the problem before I 
run into runtime problems. Also, I guess the same problem might happen (less likely) if you're adding two 32-bit integers or subtracting them... Maybe there is already some option, but I cannot find it.

     Thanks very much for your help,

     Ricardo



More information about the Libstdc++ mailing list