Skip to main content

IAR Embedded Workbench for RISC-V 3.40

MISRAC2012-Rule-18.2

In this section:
Synopsis

(Required) Subtraction between pointers shall only be applied to pointers that address elements of the same array. Note: This rule will only accept arrays of the form '<type> <name>[<size>]'.

Enabled by default

Yes

Severity/Certainty

Medium/Medium

mediummedium.png
Full description

A subtraction was found between pointers that address elements of different arrays. This check is identical to MISRAC2004-17.2, CERT-ARR36-C_a.

Coding standards
CERT ARR36-C

Do not subtract or compare two pointers that do not refer to the same array

MISRA C:2004 17.2

(Required) Pointer subtraction shall only be applied to pointers that address elements of the same array.

MISRA C:2012 Rule-18.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 <stddef.h>

void example(void) {
  int a[20];
  int b[20];
  int *p1 = &a[5];
  int *p2 = &b[2];
  ptrdiff_t diff;
  diff = p2 - p1;
}

The following code example passes the check and will not give a warning about this issue:

#include <stddef.h>

void example(void) {
  int arr[10];
  int *p1 = &arr[5];
  int *p2 = &arr[5];
  ptrdiff_t diff;
  diff = p2 - p1;
}