Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the multiplication of two unsigned shorts really lead to undefined behaviour?

I have spent some time trawling this site; in particular this question: Is ((a + (b & 255)) & 255) the same as ((a + b) & 255)?

In doing so, I've been led to the conclusion that

int main()
{
    unsigned short i = std::numeric_limits<unsigned short>::max();
    unsigned short j = i;
    auto y = i * j;
}

can lead to undefined behaviour due to a type promotion of i and j to int which subsequently overflows upon the multiplication! Perhaps i and j need not to even be this large.

My conclusion is that, for example, on a system where unsigned short is 16 bits and int is 32 bits, the behaviour can be undefined.

Am I correct here?

like image 826
Fitzwilliam Bennet-Darcy Avatar asked Nov 24 '16 11:11

Fitzwilliam Bennet-Darcy


People also ask

How do you know if a multiplication will overflow?

If either of the number is 0, then it will never exceed the range. Else if the product of the two divided by one equals the other, then also it will be in range. In any other case overflow will occur.

How do you stop overflow multiplication in C++?

We need to split numbers to avoid overflow.


1 Answers

Yes, it's possible, and your example is likely to be undefined on most desktop architectures.

For the sake of this example, let's assume that int is 32-bit 2's complement type and unsigned short is 16-bit.

I'm using N4140 for the quotes.

Before multiplication, both values are promoted to int:

§ 4.5 [conv.prom] / 1

A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type;

Then:

§ 5 [expr] / 4

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.

Since the result of 65535 * 65535 (4294836225) is not defined in our 32-bit int (with value range [-2147483648,2147483647]), the behaviour is undefined.

like image 100
krzaq Avatar answered Sep 17 '22 21:09

krzaq