MISRA C:2012 Rule 18.2
Subtraction between pointers shall only be applied to pointers that address elements of the same array
Description
Rule Definition
Subtraction between pointers shall only be applied to pointers that address elements of the same array1 .
Rationale
This rule applies to expressions of the form pointer_expression1
- pointer_expression2
. The behavior is undefined if pointer_expression1
and pointer_expression2
:
Do not point to elements of the same array,
Or do not point to the element one beyond the end of the array.
Polyspace Implementation
Polyspace® reports a violation of this rule when you subtract pointers that are null or that point to elements in different arrays.
If one of the pointers in the subtraction 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(); int diff = c_str - arg_ptr; //No violation int diff2 = c_str - tmp; //No violation }
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
Check Information
Group: Pointers and Arrays |
Category: Required |
AGC Category: Required |
Version History
1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.