Search code examples
c++cppcheck

Cppcheck: Out of bounds access because "container is empty" but container is not empty


I have this simple test code that creates a vector of two elements and prints it's size, then prints the first element:

#include <vector>
#include <iostream>

using namespace std;

int main() {
    vector<double> arr {0, 0.1};
    cout << arr.size() << endl;
    cout << arr[0] << endl;
}

The code compiles and runs fine and outputs 2 then 0 as it should.

However when I run Cppcheck on this file it reports this:

error: Out of bounds access in expression 'arr[0]' because 'arr' is empty. [containerOutOfBounds]
 cout << arr[0] << endl;
            ^

But arr is clearly not empty!

Is this a false positive or am I missing something?

Running with Cppcheck version 2.12


Solution

  • This seems to be another cppcheck bug/defect. There was similar issue some years ago.

    Here is the old issue:

    Out of bounds access in expression 'test_array[0]' because 'test_array' is empty.