Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

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

1   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 example

1   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.

Extension

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