ITER.END.DEREF.MIGHT

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

Copy
   #include <set>
   using namespace std;
   int foo(set<int>& cont)
   {
     set<int>::iterator i = cont.begin();
     if (*i < 100)
       return *i;
     return 100;
   } 

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

Copy
   int foo(set<int>& cont)
   {
     set<int>::iterator i = cont.begin();
     if ( (i != cont.end()) && (*i < 100) )
       return *i;
     return 100;
   } 

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

Extension

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