Versions Compared

Key

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

...

In this noncompliant code example, the for loop uses array subscripting. Since arry array subscripts are computed using pointer arithmetic, this code also results in undefined behavior.

...

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:.

Code Block
bgColor#ccccff
langcpp
#include <iostream>

// ... definitions for S, T, globI, globD ...

void f(const S * const *someSes, std::size_t count) { 
  for (const S * const *end = someSes + count; someSes != end; ++someSes) {
    std::cout << (*someSes)->i << std::endl;
  }
}

int main() {
  S *test[] = {new T, new T, new T, new T, new T};
  f(test, 5);
  for (auto v : test) {
    delete v;
  }
}

...

Using arrays polymorphically can result in memory corruption, which could lead to an attacker being able to execute arbitrary code.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CTR56-CPP

High

Likely

High

P9

L2

Automated Detection

Tool

Version

Checker

Description

Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC++-CTR56
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

LANG.STRUCT.PARITH

Pointer Arithmetic

Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C++3073
Parasoft C/C++test
9.5PB-10, STL-02  
Include Page
Parasoft_V
Parasoft_V

CERT_CPP-CTR56-a
CERT_CPP-CTR56-b
CERT_CPP-CTR56-c

Don't treat arrays polymorphically
A pointer to an array of derived class objects should not be converted to a base class pointer
Do not treat arrays polymorphically

LDRA tool suite
Include Page
LDRA_V
LDRA_V

567 S

Enhanced Enforcement

 PRQA QA-

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C++: CTR56-CPPChecks for pointer arithmetic on polymorphic object (rule fully covered)
PVS-Studio

Include Page

PRQA QA-C++

PVS-Studio_V

PRQA QA-C++

PVS-Studio_V

3072, 3073
V777
 

Related Vulnerabilities

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

Related Guidelines

Bibliography

[ISO/IEC 14882-2014]

Subclause 5.7, "Additive Operators"
Subclause 5.2.1, "Subscripting" 

[Lockheed Martin
05
2005]AV Rule 96, "Arrays shall not be treated polymorphically"
[Meyers
96
1996]Item 3, "Never Treat Arrays Polymorphically"
[Stroustrup
06
2006]"What's Wrong with Arrays?"
[Sutter
04
2004]Item 100, "Don't Treat Arrays Polymorphically"

...


...

Image Modified Image Modified Image Modified