GameNetworkingSockets icon indicating copy to clipboard operation
GameNetworkingSockets copied to clipboard

Multiplication result converted to larger type

Open odaysec opened this issue 9 months ago • 0 comments

https://github.com/ValveSoftware/GameNetworkingSockets/blob/725e273c7442bac7a8bc903c0b210b1c15c34d92/src/tier1/utlmemory.cpp#L21-L21

This rule finds code that converts the result of an integer multiplication to a larger type. Since the conversion applies after the multiplication, arithmetic overflow may still occur. The rule flags every multiplication of two non-constant integer expressions that is (explicitly or implicitly) converted to a larger integer type. The conversion is an indication that the expression would produce a result that would be too large to fit in the smaller integer type.

POC

int i = 2000000000;
long j = i * i; //Wrong: due to overflow on the multiplication between ints, 
                //will result to j being -1651507200, not 4000000000000000000

long k = (long) i * i; //Correct: the multiplication is done on longs instead of ints, 
                       //and will not overflow

long l = static_cast<long>(i) * i; //Correct: modern C++

References

odaysec avatar Feb 28 '25 06:02 odaysec