Main Content

MISRA C:2023 Rule 18.3

The relational operators >, >=, < and <= shall not be applied to expressions of pointer type except where they point into the same object

Since R2024a

Description

Rule Definition

The relational operators >, >=, <, and <= shall not be applied to expressions of pointer type except where they point into the same object.

Rationale

If two pointers do not point to the same object, comparisons between the pointers produces undefined behavior.

You can address the element beyond the end of an array, but you cannot access this element.

Polyspace Implementation

Polyspace® reports a violation of this rule when you compare pointers that are null or that point to elements in different arrays. The relational operators for the comparison are >, <, >=, and <=.

If one of the pointers in the comparison operation is unknown to Polyspace in the current analysis, a violation of this rule is not reported. For example, in this code, Polyspace cannot determine the underlying objects of arg_ptr and temp:

extern int *getPtr();
void foo(int *arg_ptr) {
	int diff, diff2;
	int c_str[50];
	int *temp = getPtr();

	if(c_str < arg_ptr) {/**/} //No violation
	if(c_str < tmp) {/**/} //No violation
}
The comparison involving these pointers are not reported as violations of this rule.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

void f1(void){
    int arr1[10];
    int arr2[10];
    int *ptr1 = arr1;

    if(ptr1 < arr2){}    /* Non-compliant */
    if(ptr1 < arr1){}    /* Compliant */
}

In this example, ptr1 is a pointer to arr1. To be compliant with rule 18.3, you can compare only ptr1 with arr1. Therefore, the comparison between ptr1 and arr2 is noncompliant.

struct limits{
  int lower_bound;
  int upper_bound;
};

void func2(void){
    struct limits lim_1 = { 2, 5 };
    struct limits lim_2 = { 10, 5 };

    if(&lim_1.lower_bound <= &lim_2.upper_bound){}  /* Non-compliant *
    if(&lim_1.lower_bound <= &lim_1.upper_bound){}  /* Compliant */
}

This example defines two limits structures, lim1 and lim2, and compares the elements. To be compliant with rule 18.3, you can compare only the structure elements within a structure. The first comparison compares the lower_bound of lim1 and the upper_bound of lim2. This comparison is noncompliant because the lim_1.lower_bound and lim_2.upper_bound are elements of two different structures.

Check Information

Group: Pointers and Arrays
Category: Required
AGC Category: Required

Version History

Introduced in R2024a