ITER.CONTAINER.MODIFIEDInvalid iteratorThe 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 riskUsing 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 example1 void foo(list<int>& cont, int x) 2 { 3 list<int>::iterator i; 4 for (i = cont.begin(); i != cont.end(); i++) 5 { 6 if (*i == x) 7 cont.erase(i); 8 } 9 } 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 example1 void foo(list<int>& cont, int x) 2 { 3 list<int>::iterator i; 4 for (i = cont.begin(); i != cont.end();) 5 { 6 if (*i == x) 7 i =cont.erase(i); 8 else i++; 9 } 10 } In the fixed example, the iterator is reassigned after the invalidation. Related checkersExtensionThis checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information. |