MISRAC++2008-5-0-17
In this section:
Synopsis
(Required) Subtraction between pointers shall only be applied to pointers that address elements of the same array.
Enabled by default
Yes
Severity/Certainty
High/Medium

Full description
Subtracting pointers of different arrays may lead to undefined behaviour. This check is identical to MISRAC++2023-8.7.2.
Coding standards
- MISRA C++ 2023 8.7.2
(Required) Subtraction between pointers shall only be applied to pointers that address elements of the same array
Code examples
The following code example fails the check and will give a warning:
#include <cstddef>
void example( int * ptr ) {
int a1[10];
int * p1 = &a1[1];
std::ptrdiff_t diff = ptr - p1; // Non-compliant
}
The following code example passes the check and will not give a warning about this issue:
#include <cstddef>
void example() {
int a1[10];
int * p1 = &a1[1];
std::ptrdiff_t diff = p1 - a1; // Compliant
}