V2559. MISRA. Subtraction, >, >=, <, <= should be applied only to pointers that address elements of the same array.


This diagnostic rule is based on the software development guidelines developed by MISRA (Motor Industry Software Reliability Association).

The C/C++ standard specifies (C11 § 6.5.8 paragraph 5; C++17 § 8.5.9 paragraph 3) that applying the operator '-', '>', '>=', '<', or '<=' to two pointers that do not point to the elements of the same array is undefined/unspecified behavior. Therefore, if two pointers point to different array objects, then these objects must be elements of the same array to be comparable.

Example of non-compliant code:

int arr1[10];
int arr2[10];
int *pArr1 = arr1;
if (pArr1 < arr2)
{
  ....
}

The following code is also non-compliant:

int arr1[10];
int arr2[10];
int *pArr1 = &arr1[1];
int *pArr2 = &arr2[1];
int len = pArr1 - pArr2;

To learn more about why pointer comparisons may lead to errors, see the article: "Pointers are more abstract than you might expect in C".


Bugs Found

Checked Projects
372
Collected Errors
13 634