CERT-ARR36-C_a
In this section:
Synopsis
Do not subtract two pointers that do not refer to the same array.
Enabled by default
Yes
Severity/Certainty
Medium/Medium

Full description
Do not subtract or compare two pointers that do not refer to the same array. This check is identical to MISRAC2004-17.2, MISRAC2012-Rule-18.2.
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>
enum { SIZE = 32 };
void func(void) {
int nums[SIZE];
int end;
int *next_num_ptr = nums;
size_t free_elements;
/* Increment next_num_ptr as array fills */
free_elements = &end - next_num_ptr;
}
The following code example passes the check and will not give a warning about this issue:
#include <stddef.h>
enum { SIZE = 32 };
void func(void) {
int nums[SIZE];
int *next_num_ptr = nums;
size_t free_elements;
/* Increment next_num_ptr as array fills */
free_elements = &(nums[SIZE]) - next_num_ptr;
}