Versions Compared

Key

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

When iterating over elements of a container, the iterators used must iterate over a valid range. An iterator range is a pair of iterators that refer to the first and past-the-end elements of the range , respectively.

A valid iterator range is a range wherehas all of the following characteristics:

Accessing two iterators which that do not refer into the same container or accessing invalidated iterators results in undefined behavior.

Several generic standard template library (STL) algorithms, such as std::remove() and std::unique(), remove instances of elements from a container without shrinking the size of the container. Instead, these algorithms return a ForwardIterator to indicate the partition within the container after which elements are no longer valid. The elements in the container that precede the returned iterator are valid elements with specified values, while whereas the elements that succeed the returned iterator are valid but have unspecified values. Accessing unspecified values of elements iterated over results in unspecified behavior. Frequently, the erase-remove idiom is used to shrink the size of the container when using these algorithms.

...

In this noncompliant example, the two iterators that delimit the range point into the same container, but the first iterator doesn't does not precede the second. On each iteration of its internal loop, std::for_each() compares the first iterator with the second for equality, and as long as they are not equal, it will continue to increment the first iterator. Incrementing the iterator representing the past-the-end element of the range results in undefined behavior.

...

In this noncompliant code example, iterators from different containers are passed for the same iterator range. While Although many STL implementations will compile this code and exhibit reasonable behavior, there is no requirement that an STL implementation treat a default-initialized iterator as a synonym for end().

...

In this compliant solution, elements removed by the standard algorithm are subsequently erased from the given container. This technique ensures that a valid iterator range is used by the range-based for loop.

...

Tool

Version

Checker

Description

    

Related Vulnerabilities

The In fun with erase() article by , Chris Rohlf discusses the exploit potential of a program that calls vector::erase() with invalid iterator ranges.

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

Related Guidelines

...