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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With