ITER.ADVANCE.NONADJACENT

Advancing iterator by a distance of more than 1

A defect will be reported for use of the following functions to advance an iterator with the last argument other than -1, 0, 1:

  • operator+

  • operator+=

  • operator-

  • operator-=

  • std::prev

  • std::next

Vulnerability and risk

Buffer overflow is the most common security vulnerability, and this defect is a subclass of that vulnerability: C++ STL specific.

Vulnerable code example

Copy
#include <vector>
#include <iterator>
 
void noncompliant (const std::vector<int> & c)
{
  const size_t dist = 20;
  auto it = std::next (c.begin (), dist);
}

Klocwork reports defect ITER.ADVANCE.NONADJACENT on line 7 stating "Iterator 'c.begin()' is incremented or decremented by more than 1 at line 7". Iterator 'it' is advanced by a distance of 20.

Fixed code example

Copy
#include <algorithm>
 
void compliant (const std::vector<int> & c)
{
  const size_t dist = 20;
  auto it = std::next (c.begin (), std::min (dist, c.size ()));
}

The distance argument is no longer a fixed value, and in this case it is guaranteed to be valid.

Related checkers