Menu ▾ ▴

False negative: invalidated iterator accessed through explicit operator++

Rodri
2026-09-29
2026-09-30
  • Rodri

    Rodri - 2026-09-29

    Hi, I found a false negative regarding the rule invalidContainer.

    Cppcheck misses the use of an invalidated vector iterator when the increment is written as an explicit operator call.

    #include <vector>
    
    void f() {
      std::vector<int> items{1, 2, 3};
      std::vector<int>::iterator iter;
      for (iter = items.begin(); iter != items.end(); iter.operator++()) {
        if (*iter == 2)
          items.erase(iter);
      }
    }
    

    Actual result

    Cppcheck does not report invalidContainer. Replacing iter.operator++() with ++iter produces the warning. Using ++(iter) also misses the warning.

    Expected result

    Cppcheck should report the use of the invalidated iterator regardless of the increment spelling.

    Verification

    The issue was reproduced with:

    cppcheck --output-format=xmlv2 --enable=all invalid_iterator.cpp
    

    Version: 2.21.0

     
  • CHR

    CHR - 2026-09-30

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/15076

     

Log in to post a comment.