This diagnostic rule is based on the MISRA (Motor Industry Software Reliability Association) software development guidelines.
This diagnostic rule is relevant only for C.
Pointer subtraction is allowed only when both pointers address elements of the same array or the element immediately following the last element of that array.
If the pointers address different arrays or objects, the program's behavior is undefined (C11, § 6.5.6.9).
The example:
void example(void)
{
int32_t a[10];
int32_t b[10];
int32_t *ptr1 = a;
int32_t *ptr2 = b + 10;
ptrdiff_t offset = ptr2 - ptr1; // <=
// ....
}
The code calculates the distance between the beginning of the first array and the end of the second. The standard guarantees pointer arithmetic only for two pointers that address the same array object. As a result, this type of pointer arithmetic leads to undefined behavior.
This diagnostic rule is classified as:
|
Was this page helpful?
Your message has been sent. We will email you at
If you do not see the email in your inbox, please check if it is filtered to one of the following folders: