Bad check for overflow of integer addition¶
ID: cpp/bad-addition-overflow-checkKind: problemSecurity severity: 8.1Severity: errorPrecision: very-highTags: - reliability - correctness - security - external/cwe/cwe-190 - external/cwe/cwe-192Query suites: - cpp-code-scanning.qls - cpp-security-extended.qls - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
Checking for overflow of integer addition needs to be done with care, because automatic type promotion can prevent the check from working as intended, with the same value (true orfalse) always being returned.
Recommendation¶
Use an explicit cast to make sure that the result of the addition is not implicitly converted to a larger type.
Example¶
boolcheckOverflow(unsignedshortx,unsignedshorty){// BAD: comparison is always false due to type promotionreturn(x+y<x);}
On a typical architecture whereshort is 16 bits andint is 32 bits, the operands of the addition are automatically promoted toint, so it cannot overflow and the result of the comparison is always false.
The code below implements the check correctly, by using an explicit cast to make sure that the result of the addition isunsignedshort (which may overflow, in which case the comparison would evaluate totrue).
boolcheckOverflow(unsignedshortx,unsignedshorty){return((unsignedshort)(x+y)<x);// GOOD: explicit cast}