CodeQL documentation

Multiplication result converted to larger type

ID: cpp/integer-multiplication-cast-to-long
Kind: problem
Severity: warning
Precision: high
Tags:
   - reliability
   - security
   - correctness
   - types
   - external/cwe/cwe-190
   - external/cwe/cwe-192
   - external/cwe/cwe-197
   - external/cwe/cwe-681
Query suites:
   - cpp-code-scanning.qls
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

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.

Recommendation

Use a cast to ensure that the multiplication is done using the larger integer type to avoid overflow.

Example

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