CodeQL documentation

Unsigned difference expression compared to zero

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

Click to see the query in the CodeQL repository

This rule finds relational comparisons between the result of an unsigned subtraction and the value 0. Such comparisons are likely to be wrong as the value of an unsigned subtraction can never be negative. So the relational comparison ends up checking whether the result of the subtraction is equal to 0. This is probably not what the programmer intended.

Recommendation

If a relational comparison is intended, consider casting the result of the subtraction to a signed type. If the intention was to test for equality, consider replacing the relational comparison with an equality test.

Example

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();
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy