Menu

cppcheck 2.10 False Positive (containerOutOfBounds) with array of functions

penguish
2023-02-01
2023-02-01
  • penguish

    penguish - 2023-02-01

    False positive for array index out-of-bounds when dealing with postincremented index on an array of functions, e.g.

    #include <iostream>
    #include <array>
    #include <functional>
    
    int main(int argc, const char * argv[]) {
      unsigned roiElementNumber = 0;
      //
      std::array<std::function<int(const int)>,2> fillResultFunctors={
        [&](const int n) { return n;},
        [&](const int n) { return 100+n; }
      };
      constexpr std::array<int,3> a{1,2,3};
      //cppcheck gives false containerOutOfBounds error
      for(const auto i:a) {
          if (roiElementNumber > 1) { 
            roiElementNumber = 1; 
          }
          std::cout<<fillResultFunctors[roiElementNumber++](i)<<'\n';
      }
      std::cout<<'\n';
      //cppcheck is ok with this
      roiElementNumber=0;
      std::array<int,2> b{100,200};
      for(const auto i:a) {
          if (roiElementNumber > 1) { 
            roiElementNumber = 1; 
          }
          std::cout<<b[roiElementNumber++]<<'\n';
      }
      return 0;
    }
    
     

    Last edit: penguish 2023-02-01
  • CHR

    CHR - 2023-02-01

    Thanks for reporting, see https://trac.cppcheck.net/ticket/11530

     

Log in to post a comment.