ITER.END.DEREF.MUSTDereference of end iteratorThe 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 riskUsing an invalid iterator typically results in undefined behavior. Mitigation and preventionTo 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 example1 #include <set> 2 using namespace std; 3 int foo(set<int>& cont) 4 { 5 int x = 0; 6 set<int>::iterator i; 7 for (i = cont.begin(); i != cont.end(); i++) 8 { 9 x += *i; 10 if (x > 100) 11 break; 12 } 13 x += *i; 14 return x; 15 } 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 example1 int foo(set<int>& cont) 2 { 3 int x = 0; 4 set<int>::iterator i; 5 for (i = cont.begin(); i != cont.end(); i++) 6 { 7 x += *i; 8 if (x > 100) 9 break; 10 } 11 if (i != cont.end()) 12 x += *i; 13 return x; 14 } In the fixed example, the check added at line 11 ensures that iterator 'i' isn't equal to cont.end(). Related checkersExtensionThis checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information. |