This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 8.7.2 - Subtraction between pointers shall only be applied to pointers that address elements of the same array
[expr.add] Undefined 5
Category: Required
Analysis: Undecidable,System
Amplification
This rule applies to expressions of the form:
pointer_expression_1 - pointer_expression_2
Note: a pointer to an object that is not an array is treated as if it were a pointer to the first element of an array with a
single element.
Rationale
Undefined behaviour occurs if pointer_expression_1 and pointer_expression_2 do not point to elements of the same
array or the element one beyond the end of that array.
Example
void f1( int32_t * ptr )
{
int32_t a1[ 10 ];
int32_t a2[ 10 ];
int32_t * p1 = &a1[ 1 ];
int32_t * p2 = &a2[ 10 ];
ptrdiff_t diff1 = p1 - a1; // Compliant
ptrdiff_t diff2 = p2 - a2; // Compliant
ptrdiff_t diff3 = p1 - p2; // Non-compliant
ptrdiff_t diff4 = ptr - p1; // Non-compliant
}
Copyright The MISRA Consortium Limited © 2023