将无符号差异表达式与零进行比较¶
ID: cpp/unsigned-difference-expression-compared-zero
Kind: problem
Security severity: 9.8
Severity: warning
Precision: medium
Tags:
- security
- correctness
- external/cwe/cwe-191
Query suites:
- cpp-security-extended.qls
- cpp-security-and-quality.qls
此规则查找无符号减法结果与值 0
之间的比较关系。此类比较很可能是错误的,因为无符号减法的值永远不会为负。因此,比较关系最终会检查减法的结果是否等于 0
。这可能不是程序员的意图。
建议¶
如果需要进行比较关系,请考虑将减法的结果转换为有符号类型。如果要测试相等性,请考虑将比较关系替换为相等性测试。
示例¶
unsigned limit = get_limit();
unsigned total = 0;
while (limit - total > 0) { // wrong: if `total` is greater than `limit` this will underflow and continue executing the loop.
total += get_data();
}
参考文献¶
SEI CERT C 编码标准:INT02-C. 了解整数转换规则。
常见弱点枚举:CWE-191。