整数加法溢出检查错误¶
ID: cpp/bad-addition-overflow-check
Kind: problem
Security severity: 8.1
Severity: error
Precision: very-high
Tags:
- reliability
- correctness
- security
- external/cwe/cwe-190
- external/cwe/cwe-192
Query suites:
- cpp-code-scanning.qls
- cpp-security-extended.qls
- cpp-security-and-quality.qls
检查整数加法溢出需要谨慎,因为自动类型提升可能会阻止检查按预期工作,始终返回相同的值(true
或 false
)。
建议¶
使用显式转换以确保加法的结果不会被隐式转换为更大的类型。
示例¶
bool checkOverflow(unsigned short x, unsigned short y) {
// BAD: comparison is always false due to type promotion
return (x + y < x);
}
在 short
为 16 位,int
为 32 位的典型架构上,加法的操作数会自动提升为 int
,因此不会发生溢出,比较结果始终为假。
以下代码使用显式转换来正确地实现检查,以确保加法的结果为 unsigned short
(可能发生溢出,在这种情况下,比较将评估为 true
)。
bool checkOverflow(unsigned short x, unsigned short y) {
return ((unsigned short)(x + y) < x); // GOOD: explicit cast
}