Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Pointer arithmetic is appropriate only when the pointer argument refers to an array (see ARR37-C. Do not add or subtract an integer to a pointer to a non-array object), including an array of bytes. When performing pointer arithmetic, the size of the value to add to or subtract from a pointer is automatically scaled to the size of the type of the referenced array object. Adding or subtracting a scaled integer value to or from a pointer is invalid because it may yield a pointer that does not point to an element within or one past the end of the array. (see See ARR30-C. Do not form or use out-of-bounds pointers or array subscripts.).

Adding a pointer to an array of a type other than character to the result of the sizeof operator or offsetof macro, which return returns a size and an offset, respectively, violates this rule. However, adding an array pointer to the number of array elements, for example, by using the arr[sizeof(arr)/sizeof(arr[0])]) idiom, is allowed provided that arr refers to an array and not a pointer.

...

CERT C Secure Coding StandardARR30-C. Do not form or use out-of-bounds pointers or array subscripts
ARR37-C. Do not add or subtract an integer to a pointer to a non-array object
ISO/IEC TR 24772:2013Pointer Casting and Pointer Type Changes [HFC]
Pointer Arithmetic [RVG]
MISRA C:2012Rule 18.1 (required)
Rule 18.2 (required)
Rule 18.3 (required)
Rule 18.4 (advisory)
MITRE CWE

CWE 468, Incorrect Pointer Scaling

...