Versions Compared

Key

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

The definition of pointer arithmetic from The the C++ Standard, [expr.add], paragraph 7, states [ISO/IEC 14882-2014]:

...

Pointer arithmetic does not account for polymorphic object sizes, and attempting to perform pointer arithmetic on a polymorphic object value results in undefined behavior.

The C++ StardardStandard, [expr.sub], paragraph 1, defines array subscripting as being identical to pointer arithmetic. Specifically, it states:

The expression E1[E2] is identical (by definition) to *((E1)+(E2))...

Do not use pointer arithmetic, including array subscripting, on polymorphic objects.

...

In this noncompliant code example, f() accepts an array of S objects as its first parameter. However, main() passes an array of T objects as the first argument to f(), which results in undefined behavior due to the pointer arithmetic used within the for loop.

...

This example would still be noncompliant if the for loop had instead been written to use array subscripting, likeas in the following:

Code Block
for (std::size_t i = 0; i < Count; ++i) {
  std::cout << SomeSes[i].I << std::endl;
}

...

Another approach is to use an STL a standard template (STL) library container instead of an array and have f() accept iterators as parameters, as in this compliant solution. However, since because STL containers require homogeneous elements, pointers are still required within the container.

...

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

...

[ISO/IEC 14882-2014]

5.7, "Additive Operators"
5.2.1, "Subscripting" 

[Stroustrup 06]What's wrong with arrays?
[Meyers 06]Item 3: Never treat arrays polymorphically
[Lockheed Martin 05]AV Rule 96, Arrays shall not be treated polymorphically.
[Sutter 04]Item 100: Don't treat arrays polymorphically

...