ITER.CONTAINER.MODIFIED

Invalid iterator

The ITER checkers find problems with iterators in containers. The ITER.CONTAINER.MODIFIED checker flags instances in which an iterator is used after it's been invalidated by an operation modifying its container object.

Vulnerability and risk

Using an invalid iterator typically results in undefined behavior. For example, using an iterator after a function has modified its container can result in unexpected program actions. Code containing the iterator and modified container can become corrupted, and the algorithm won't behave as expected or intended.

Vulnerable code example

Copy
   void foo(list<int>& cont, int x)
   {
     list<int>::iterator i;
     for (i = cont.begin(); i != cont.end(); i++)
     {
       if (*i == x)
         cont.erase(i);
     }
   } 

In this example, the function is supposed to remove all elements from list 'cont' that are equal to 'x'. However, calling 'cont.erase(i)' invalidates iterator 'i', so that the subsequent incrementation of 'i' becomes an invalid operation.

Fixed code example

Copy
   void foo(list<int>& cont, int x)
   {
     list<int>::iterator i;
     for (i = cont.begin(); i != cont.end();)
     {
       if (*i == x)
         i =cont.erase(i);
       else i++;
     }
   } 

In the fixed example, the iterator is reassigned after the invalidation.

Extension

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