Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any c++ static analysis tool to detect potential bug with vector [closed]

See the following code from rust example. Is there any static analysis tool to detect this problem?

#include<iostream>
#include<vector>
#include<string>

int main() {
    std::vector<std::string> v;

    v.push_back("Hello");

    std::string& x = v[0];

    v.push_back("world");

    std::cout << x;
}
like image 404
Patrick Avatar asked Nov 09 '22 23:11

Patrick


1 Answers

The open-source program "cppcheck", fundamentally, has the ability to detect such errors. According to its description, it can detect, among other things:

[...]

  • for vectors: using iterator/pointer after push_back has been used

[...]

Unfortunately, the version I tested (1.63) does not detect the error in your code snippet. However, changing from reference to iterator creates a situation that it apparently can detect:

#include<iostream>
#include<vector>
#include<string>

int main() {
    std::vector<std::string> v;

    v.push_back("Hello");

    std::string& x = v[0];
    std::vector<std::string>::iterator it = v.begin();

    v.push_back("world");

    std::cout << *it;
}

Storing this in test.cpp and running cppcheck:

cppcheck --std=c++03 ./test.cpp

I get the output below:

Checking test.cpp...
[test.cpp:15]: (error) After push_back(), the iterator 'it' may be invalid.

I suppose that's pretty close to what you are looking for.

like image 81
jogojapan Avatar answered Nov 14 '22 21:11

jogojapan