ITER.INAPPROPRIATE
Iterator with inappropriate container object
The ITER checkers find problems with iterators in containers. The ITER.INAPPROPRIATE checker flags instances in which an iterator is assigned to one container and used with another container.
Vulnerability and risk
Using an invalid iterator typically results in undefined behavior. For example, using the iterator in the wrong container can result in unpredictable program actions. Code in which an iterator is used in an inappropriate container always provides a false result, so the algorithm won't behave as expected or intended.
Vulnerable code example
void foo(set<int>& cont1, set<int>& cont2)
{
set<int>::iterator i = cont1.find(100);
if (i != cont1.end())
cont2.erase(i);
}
In this example, iterator 'i' is assigned to container 'cont1', and then used incorrectly with 'cont2', which will produce undefined results.
Fixed code example
void foo(set<int>& cont1, set<int>& cont2)
{
set<int>::iterator i = cont1.find(100);
if (i != cont1.end())
{
i = cont2.find(100);
if (i != cont2.end())
cont2.erase(i);
}
In the fixed example, the correct iterator is retrieved for 'cont2'.
Related checkers
Extension
This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.