将乘法结果转换为更大类型¶
ID: cpp/integer-multiplication-cast-to-long
Kind: problem
Security severity: 8.1
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
此规则查找将整数乘法的结果转换为更大类型的代码。由于转换是在乘法之后应用的,因此可能仍然会发生算术溢出。
此规则标记所有两个非常量整数表达式的乘法,这些乘法(显式或隐式)转换为更大的整数类型。转换表明表达式将产生一个结果,该结果太大而无法容纳在较小的整数类型中。
建议¶
使用强制转换以确保使用较大的整数类型进行乘法,以避免溢出。
示例¶
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++