ITER.END.DEREF.MUST
Dereference of end iterator
The ITER checkers find problems with iterators in containers. The ITER.END.DEREF.MUST checker flags instances in which an iterator is explicitly checked against the value of the end() or rend() method of the container object, and then dereferenced when its value could be equal to end() or rend().
Vulnerability and risk
Using an invalid iterator typically results in undefined behavior.
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
#include <set>
using namespace std;
int foo(set<int>& cont)
{
int x = 0;
set<int>::iterator i;
for (i = cont.begin(); i != cont.end(); i++)
{
x += *i;
if (x > 100)
break;
}
x += *i;
return x;
}
If no break occurs in the loop at line 9 in this example, the value of iterator 'i' will be equal to cont.end() after the loop. In this case, dereferencing 'i' is invalid, and will produce undefined results.
Fixed code example
int foo(set<int>& cont)
{
int x = 0;
set<int>::iterator i;
for (i = cont.begin(); i != cont.end(); i++)
{
x += *i;
if (x > 100)
break;
}
if (i != cont.end())
x += *i;
return x;
}
In the fixed example, the check added at line 12 ensures that iterator 'i' isn't equal to cont.end().
Related checkers
Extension
This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.