Possible dereference of end iterator

The ITER checkers find problems with iterators in containers. The ITER.END.DEREF.MIGHT checker flags instances in which an iterator is dereferenced when its value could be equal to end() or rend(). This type of dereference may occur due to the use of the iterator despite its check, or in another branch of the program where it's hard to spot.

Vulnerability and risk

Using an invalid iterator typically results in undefined behavior. For example, dereferencing an iterator when it may be equal to end() or rend() can cause unpredictable memory access.

Mitigation and prevention

To avoid this issue, add a check to your code to make sure that the iterator isn't equal to the value of end() or rend().

Vulnerable code example

1   #include <set>
2   using namespace std;
3   int foo(set<int>& cont)
4   {
5     set<int>::iterator i = cont.begin();
6     if (*i < 100)
7       return *i;
8     return 100;
9   } 

If container 'cont' is empty in this example, the value of iterator 'i' will be equal to cont.end(). In this case, dereferencing 'i' is invalid, and will produce undefined results.

Fixed code example

1   int foo(set<int>& cont)
2   {
3     set<int>::iterator i = cont.begin();
4     if ( (i != cont.end()) && (*i < 100) )
5       return *i;
6     return 100;
7   } 

In the fixed example, the check added at line 4 ensures that iterator 'i' isn't equal to cont.end().


This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.