When two pointers are subtracted, both must point to elements of the same array object or just one past the last element of the array object (C Standard, 6.5.6 7 [ISO/IEC 9899:20112024]); the result is the difference of the subscripts of the two array elements. Otherwise, the operation is undefined behavior. (See undefined behavior 48.)
...
Tool | Version | Checker | Description | |||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Astrée |
| pointer-subtraction | Partially checked | |||||||||||||||||||
Axivion Bauhaus Suite |
| CertC-ARR36 | Can detect operations on pointers that are unrelated | |||||||||||||||||||
CodeSonar |
| LANG.STRUCT.CUP LANG.STRUCT.SUP | Comparison of Unrelated Pointers Subtraction of Unrelated Pointers | |||||||||||||||||||
Coverity |
| MISRA C 2004 17.2 MISRA C 2004 17.3 MISRA C 2012 18.2 MISRA C 2012 18.3 | Implemented | |||||||||||||||||||
Cppcheck |
| comparePointers | Fully implemented | |||||||||||||||||||
Cppcheck Premium |
| comparePointers | Fully implemented | |||||||||||||||||||
Helix QAC |
| C0487, C0513 DF2668, DF2669, DF2761, DF2762, DF2763, DF2766, DF2767, DF2768, DF2771, DF2772, DF2773 | ||||||||||||||||||||
Klocwork |
| MISRA.PTR.ARITH | ||||||||||||||||||||
LDRA tool suite |
| 437 S, 438 S | Fully implemented | |||||||||||||||||||
Parasoft C/C++test |
| CERT_C-ARR36-a | Pointer arithmetic shall only be applied to pointers that address an array or array elementCERT_C-ARR36-b | Do not subtract two pointers that do not address elements of the same array | ||||||||||||||||||
| 2012 Rule 18.2 | Checks for subtraction | Subtraction or comparison between pointers | causes undefined behaviorPRQA QA-C | ||||||||||||||||||
Include Page | PRQA QA-C_v | PRQA QA-C_v | 0487, 0513, 2771, 2772, | Fully implemented | PVS-Studio | |||||||||||||||||
Include Page | PVS-Studio_V | PVS-Studio_V | V736, V782to different arrays (rule partially covered) | |||||||||||||||||||
PVS-Studio |
| V736, V782 | ||||||||||||||||||||
RuleChecker |
| pointer-subtraction | Partially checked | |||||||||||||||||||
TrustInSoft Analyzer |
| differing_blocks | Exhaustively verified (see the compliant and the non-compliant example). |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
ARR36-C = Union(CWE-469, list) where list =
- Pointer comparisons that are not subtractions using the relational operators
<
,<=
,>=
, and>
, where the pointers do not refer to the same array
...
[Banahan 2003] | Section 5.3, "Pointers" Section 5.7, "Expressions Involving Pointers" |
[ISO/IEC 9899:20112024] | 6.5.67, "Additive Operators" |
...