Skip to main content

IAR Embedded Workbench for RISC-V 3.40

ITR-invalidated (C++ only)

In this section:
Synopsis

An iterator assigned to point into a container is used or dereferenced even though it might be invalidated.

Enabled by default

Yes

Severity/Certainty

High/Medium

highmedium.png
Full description

An iterator is assigned to point into a container, but later modifications to that container might have invalidated the iterator. The iterator is then used or dereferenced, which might be undefined behavior. Like pointers, iterators must point to a valid memory address to be used. When a container is modified by member functions such as insert or erase, some iterators might become invalidated and therefore risky to use. Any function that can remove elements, and some functions that add elements, might invalidate iterators. Iterators should be reassigned into a container after modifications are made and before they are used again, to ensure that they all point to a valid part of the container.

Coding standards
CERT ARR32-CPP

Do not use iterators invalidated by container modification

CWE 119

Improper Restriction of Operations within the Bounds of a Memory Buffer

CWE 672

Operation on a Resource after Expiration or Release

Code examples

The following code example fails the check and will give a warning:

#include <vector>

void example(){
  std::vector<int> a(5,6);
  std::vector<int>::iterator i;
  
  i = a.begin();
  while (i != a.end()){
    a.erase(i);
    ++i;
  }
}

The following code example passes the check and will not give a warning about this issue:

#include <vector>

void example(){
  std::vector<int> a(5,6);
  std::vector<int>::iterator i;
  
  i = a.begin();
  while (i != a.end()){
    i = a.erase(a.begin());
  }
}