C and C++


LANG.STRUCT.SUP : Subtraction of Unrelated Pointers

Summary

Pointer subtraction is performed between pointers to different objects.

Pointer subtraction should only be performed between pointers that point at different elements of the same array. Subtracting pointers that point at different variables or allocations is undefined behavior according to the C and C++ standards.

Properties

Class Name Subtraction of Unrelated Pointers
Significance reliability
Mnemonic LANG.STRUCT.SUP
Categories
MisraC2023 MisraC2023:18.2 Subtraction between pointers shall only be applied to pointers that address elements of the same array
Misra2012 Misra2012:18.2 Subtraction between pointers shall only be applied to pointers that address elements of the same array
Misra2004 Misra2004:17.2 Pointer subtraction shall only be applied to pointers that address elements of the same array
  Misra2004:17.4 Array indexing shall be the only allowed form of pointer arithmetic
AUTOSARC++14 AUTOSARC++14:M5-0-15 Array indexing shall be the only form of pointer arithmetic.
  AUTOSARC++14:M5-0-17 Subtraction between pointers shall only be applied to pointers that address elements of the same array.
MisraC++2008 MisraC++2008:5-0-15 Array indexing shall be the only form of pointer arithmetic.
  MisraC++2008:5-0-17 Subtraction between pointers shall only be applied to pointers that address elements of the same array.
MisraC++2023 MisraC++2023:8.7.2 Subtraction between pointers shall only be applied to pointers that address elements of the same array
CWE CWE:469 Use of Pointer Subtraction to Determine Size
TS17961 TS17961:5.35-ptrobj 5.35. Subtracting or comparing two pointers that do not refer to the same array
CERT-C CERT-C:ARR36-C Do not subtract or compare two pointers that do not refer to the same array
  CERT-C:EXP08-C Ensure pointer arithmetic is used correctly
CERT-CPP CERT-CPP:CTR54-CPP Do not subtract iterators that do not refer to the same container
Availability Available for C and C++.
Enabling Checks for this warning class are enabled by default. To disable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += discard class="Subtraction of Unrelated Pointers"

Example

int f()
{
    int i, j;
    return (int)(&i - &j); /* 'Subtraction of Unrelated Pointers' warning issued here */
}

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.