The definition of pointer arithmetic from the C++ Standard, [expr.add], paragraph 7 [ISO/IEC 14882-2014], states the following:
For addition or subtraction, if the expressions
Qhave type “pointer to cv
Tis different from the cv-unqualified array element type, the behavior is undefined. [Note: In particular, a pointer to a base class cannot be used for pointer arithmetic when the array contains objects of a derived class type. —end note]
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++ Standard, [expr.sub], paragraph 1 [ISO/IEC 14882-2014], defines array subscripting as being identical to pointer arithmetic. Specifically, it states the following:
E1[E2]is identical (by definition) to
Do not use pointer arithmetic, including array subscripting, on polymorphic objects.
The following code examples assume the following static variables and class definitions.
Noncompliant Code Example (Pointer Arithmetic)
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
Noncompliant Code Example (Array Subscripting)
In this noncompliant code example, the
for loop uses array subscripting. Since array subscripts are computed using pointer arithmetic, this code also results in undefined behavior.
Compliant Solution (Array)
Instead of having an array of objects, an array of pointers solves the problem of the objects being of different sizes, as in this compliant solution.
The elements in the arrays are no longer polymorphic objects (instead, they are pointers to polymorphic objects), and so there is no undefined behavior with the pointer arithmetic.
Compliant Solution (
Another approach is to use a standard template library (STL) container instead of an array and have
f() accept iterators as parameters, as in this compliant solution. However, because STL containers require homogeneous elements, pointers are still required within the container.
Using arrays polymorphically can result in memory corruption, which could lead to an attacker being able to execute arbitrary code.
|Axivion Bauhaus Suite|
Don't treat arrays polymorphically
|LDRA tool suite|
Subclause 5.7, "Additive Operators"
|[Lockheed Martin 2005]||AV Rule 96, "Arrays shall not be treated polymorphically"|
|[Meyers 1996]||Item 3, "Never Treat Arrays Polymorphically"|
|[Stroustrup 2006]||"What's Wrong with Arrays?"|
|[Sutter 2004]||Item 100, "Don't Treat Arrays Polymorphically"|