CodeQL documentation

Pointer overflow check

ID: cpp/pointer-overflow-check
Kind: problem
Security severity: 2.1
Severity: error
Precision: high
Tags:
   - reliability
   - security
   - external/cwe/cwe-758
Query suites:
   - cpp-code-scanning.qls
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

When checking for integer overflow, you may often write tests like p + i < p. This works fine if p and i are unsigned integers, since any overflow in the addition will cause the value to simply “wrap around.” However, using this pattern when p is a pointer is problematic because pointer overflow has undefined behavior according to the C and C++ standards. If the addition overflows and has an undefined result, the comparison will likewise be undefined; it may produce an unintended result, or may be deleted entirely by an optimizing compiler.

Recommendation

To check whether an index i is less than the length of an array, simply compare these two numbers as unsigned integers: i < ARRAY_LENGTH. If the length of the array is defined as the difference between two pointers ptr and p_end, write i < p_end