主要内容

Out of bound access of C++ standard library containers

Index of C++ Standard template Library (STL) container out of bounds during container access using standard operators or methods

Since R2026a

Description

This defect occurs if an out of bounds element of these containers are accessed using one of the listed operators or methods:

  • std::arraystd::array::operator[], std::array::front, std::array::back

  • std::vectorstd::vector::operator[], std::vector::push_back, std::vector::pop_back

  • std::dequestd::deque::operator[], std::deque::push_back, std::deque::pop_back, std::deque::push_front, std::deque::pop_front

Risk

Accessing a container outside its bounds is undefined behavior.

Fix

To fix this issue, check the bounds of a container before accessing them. When iterating over containers, avoid using c-style for loops. Instead, use range based for loops that manages the bounds automatically.

Examples

expand all

In this example, the function printArrayElements() prints each element of an std::array container. The upper bound of the for loop is beyond the bounds of the container by one. Polyspace® reports a defect on the [] operator.

#include <array>
#include <iostream>

void printArrayElements() {
    std::array<int, 5> arr = {1, 2, 3, 4, 5};

    // Off-by-one error
    for (size_t i = 0; i <= arr.size(); ++i) {
        std::cout << arr[i] << std::endl; // Defect
    }
}

Correction — Use correct loop upper bound

To fix this defect, change the upper limit of the loop.

#include <array>
#include <iostream>

void printArrayElements() {
    std::array<int, 5> arr = {1, 2, 3, 4, 5};

    // Off-by-one error fixed
    for (size_t i = 0; i < arr.size(); ++i) {
        std::cout << arr.at(i) << std::endl; // No defect
    }
}
The code also uses the at() operator to access the container elements. If the element is out of bounds, use of at() results in a runtime exception, which makes this bug easier to detect.

Result Information

Group: Programming
Language: C++
Default: On
Command-Line Syntax: CONTAINER_STD_LIB
Impact: High
PQL Name: std.defects.CONTAINER_STD_LIB

Version History

Introduced in R2026a