AUTOSAR C++14 Rule M5-0-15

Array indexing shall be the only form of pointer arithmetic

Description

Rule Definition

Array indexing shall be the only form of pointer arithmetic.

Rationale

You can traverse an array or container in two ways:

  • Increment or decrement an array index or an iterator, and then use the array index or iterator to access an element.

  • Increment or decrement a pointer to the array and then dereference the pointer.

The first method is clearer and less error-prone.

All other forms of explicit pointer arithmetic introduce the risk of accessing unintended memory locations.

Polyspace Implementation

The checker flags:

  • Arithmetic operations on all pointers, for instance p+I, I+p and p-I, where p is a pointer and I an integer.

    An exception is allowed for iterators that point to elements in containers, for instance, it below:

    std::vector<int> intList{ 1,2,3,4 };
    for( auto it = intList.begin() ; it != intList.end() ; ++it )

  • Array indexing on nonarray pointers.

Troubleshooting

If you expect a rule violation but do not see it, refer to the documentation for Polyspace® Bug Finder™ or Polyspace Bug Finder Server™.

Check Information

Group: Expressions
Category: Required, Automated
Introduced in R2019a