Compiler warning
Jonathan Wakely
jwakely.gcc@gmail.com
Thu Jul 31 09:18:00 GMT 2014
On 31 July 2014 10:04, Ricardo Telichevesky wrote:
> Hi,
>
> Hope this is the right place to ask this question.
No, this list is for discussion of the C++ standard library
implementation in GCC. The gcc-help@gcc.gnu.org list is the right
place, please take any follow up there.
> 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
Are you sure?
> 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,
Right, but sizeof(double) has type size_t, so the expressions are equivalent.
> 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.
That warning would trigger all the time for any multiplication, even
when multiplying values that are always small.
> I found the -ftrapv option,
-ftrapv is currently not 100% reliable and wouldn't help with the code
above as it only deals with signed integer overflow, your example
above uses unsigned types which cannot overflow. The wrapping
behaviour of unsigned integers is well-defined and often a desirable
property.
> 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...
It can happen for potentially *any* integer operation when the
operands are not constants with known values.
> Maybe
> there is already some option, but I cannot find it.
I don't know of one.
More information about the Libstdc++
mailing list