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 undefined behavior 48.)
Comparing pointers using the equality operators
!= 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.
Noncompliant Code Example
In this noncompliant code example, pointer subtraction is used to determine how many free elements are left in the
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.
In this compliant solution, the number of free elements is computed by subtracting
next_num_ptr from the address of the pointer past the
nums array. While this pointer may not be dereferenced, it may be used in pointer arithmetic.
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.
MISRA C 2004 17.2
MISRA C 2004 17.3
MISRA C 2012 18.2
MISRA C 2012 18.3
|LDRA tool suite|
437 S, 438 S
|Parasoft C/C++test||10.3||MISRA2004-17_2||Fully implemented|
|R2017b||Subtraction or comparison between pointers to different arrays||Subtraction or comparison between pointers causes undefined behavior|
0487, 0513, 2771, 2772,
Key here (explains table format and definitions)
|CERT C||CTR54-CPP. Do not subtract iterators that do not refer to the same container||Prior to 2018-01-12: CERT: Unspecified Relationship|
|ISO/IEC TS 17961||Subtracting or comparing two pointers that do not refer to the same array [ptrobj]||Prior to 2018-01-12: CERT: Unspecified Relationship|
|CWE 2.11||CWE-469, Use of Pointer Subtraction to Determine Size||2017-07-10: CERT: Exact|
|[Banahan 2003]||Section 5.3, "Pointers"|
Section 5.7, "Expressions Involving Pointers"
6.5.6, "Additive Operators"