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 [ISO/IEC 9899:2011]); the result is the difference of the subscripts of the two array elements. Otherwise, the operation is undefined behavior. (see See undefined behavior 48.).
Similarly, comparing pointers using the relational operators <, <=, >=, and > gives the positions of the pointers relative to each other. Subtracting or comparing pointers that do not refer to the same array is undefined behavior. (see See undefined behavior 48 and undefined behavior 53.).
Comparing pointers using the equality operators == and != has well-defined semantics regardless of whether or not either of the pointers is null, points into the same object, or points one past the last element of an array object or function.
...
This program incorrectly assumes that the nums array is adjacent to the end variable in memory. A compiler is permitted to insert padding bits between these two variables , or even reorder them in memory.
...
ARR36-C-EX1: Comparing two pointers to distinct members of the same struct object is allowed. Pointers to structure members declared later in the structure compare greater-than pointers to members declared earlier in the structure.
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| 437 S, 438 S | Fully implemented | |||||||
| Parasoft C/C++test | 9.5 | MISRA2008-5_0_17 | Fully implemented | ||||||
| PRQA QA-C |
| 0487, 2771, 2772, | Fully implemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.dduu
Related Guidelines
| SEI CERT C++ Coding Standard | CTR54-CPP. Do not subtract iterators that do not refer to the same container |
| ISO/IEC TS 17961 | Subtracting or comparing two pointers that do not refer to the same array [ptrobj] |
| MITRE CWE | CWE-469, Use of Pointer Subtraction to Determine Size |
...