Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cppcheck error : Dangerous iterator usage

The code:

for(x=abc.begin();x!=abc.end();x++)  
{  
   if(-----)  
   {
      ----  
      abc.erase(x);  
   }
}

And the error is :::
Dangerous iterator usage
After erase the iterator is invalid so dereferencing it or comparing it with another iterator is invalid.

what is the wrong usage in using erase function in the above code?

like image 762
eklmp Avatar asked Mar 14 '11 06:03

eklmp


2 Answers

The itarator x is invalid after deleting the corresponding value from abc. This should fix it:

x = abc.begin();

while(x != abc.end())
{
    if (-----)
    {
        ----
        x = abc.erase(x);
        // skipped only to next item
    }
    else
    {   // skip only to next item
        ++x;
    }
}

The erase template functions of STL containers return the next element, or end().

Edit: Thanks for comment by templatetypedef.

like image 54
harper Avatar answered Sep 22 '22 07:09

harper


You're using x as the control variable in the loop. Since it is invalidated by erase(), you cannot be sure that it is safe (or meaningful) to subsequently increment it at the top of the loop.

like image 34
Stabledog Avatar answered Sep 23 '22 07:09

Stabledog