AUTOSAR C++14 Rule A5-2-5
Description
Rule Definition
An array or container shall not be accessed beyond its range.
Rationale
An array or container accessed beyond its range results in undefined behavior. This rule applies to C-style arrays and all other containers where you access the array or container elements by using an iterator (including pointers) or an index.
To avoid undefined behavior, use appropriate safeguards in your code to make sure that you access the array or container within its range. For example:
Perform a range check explicitly.
Use a built-in standard template library (STL) function that performs a range check, such as
array::at()
.Use a range-based for loop when appropriate to iterate through the elements of an array or container.
Pointing to one-past the last element of the array or container is well defined, but dereferencing that element is not.
Polyspace Implementation
Polyspace® flags these issues when you enable this rule checker:
You access a C-style array beyond its range. For instance:
#include <iostream> void func() { int idx, arr[10]; for (idx = 0; idx < 10; ++idx) { arr[idx] = 2 * idx; } // idx = 10 after for loop std::cout << arr[idx]; //Noncompliant }
You use an unsanitized tainted value as an index to access an element of a C-style array. For instance, in this code snippet, variable
idx
is obtained from the environment list and is used to access an element of arrayarr2
. The value ofidx
is not checked and might be outside the range of the array:Polyspace considers that data from all external sources are tainted. For information about tainted data sources, see Sources of Tainting in a Polyspace Analysis.#include <iostream> extern int arr2[50]; void printElem() { int idx = strtol(getenv("INDEX"), NULL, 10); std::cout << arr2[idx]; //Noncompliant }
Extend Checker
Extend this checker to check for defects caused by specific values and external inputs. For instance:
A default Bug Finder analysis might not raise a defect when the input values are unknown and only a subset of inputs can cause an issue. To check for defects caused by specific system input values, run a stricter Bug Finder analysis. See Extend Bug Finder Checkers to Find Defects from Specific System Input Values.
By default, Polyspace assumes that data from external sources are tainted. See Sources of Tainting in a Polyspace Analysis. To consider any data that does not originate in the current scope of Polyspace analysis as tainted, use the command line option
-consider-analysis-perimeter-as-trust-boundary
.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Expressions |
Category: Required, Automated |
Version History
Introduced in R2022a