CXX.ITER.END.BEGIN

Iterator representing end of the range precedes start of range

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. The iterator representing the start of the range should precede the iterator representing the end of the range.

Mitigation and prevention

Ensure the iterators representing the start and end of the range are provided in the correct sequence.

Vulnerable code example

Copy
void f(const std::vector<int> &c) {
        std::for_each(c.end(), c.begin(), [](int i) { std::cout << i; });
}

In the above code, the two iterators point to the same container, but the begin() iterator is not before the end() iterator. In the loop of the inner loop, std::for_each() compares the iterator passed as the first argument with the iterator passed as the second argument. Keep incrementing the first iterator passed unless the two iterators are identical. However, in the above code, when the first iterator passed is an end() iterator, when it is increased, it exceeds the range of the vector and causes undefined behavior.