Pat*_*ick 5 c++ static-analysis vector
请参阅rust示例中的以下代码.有没有静态分析工具来检测这个问题?
#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;
}
Run Code Online (Sandbox Code Playgroud)
开源程序“cppcheck”从根本上来说具有检测此类错误的能力。根据其描述,它可以检测以下内容:
[...]
- 对于向量:使用push_back后使用迭代器/指针
[...]
不幸的是,我测试的版本(1.63)没有检测到您的代码片段中的错误。然而,从引用更改为迭代器会产生一种它显然可以检测到的情况:
#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;
}
Run Code Online (Sandbox Code Playgroud)
将其存储在test.cpp
并运行 cppcheck:
cppcheck --std=c++03 ./test.cpp
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
Checking test.cpp...
[test.cpp:15]: (error) After push_back(), the iterator 'it' may be invalid.
Run Code Online (Sandbox Code Playgroud)
我想这与您正在寻找的非常接近。