use*_*788 1 c++ string iterator vector c++11
我在迭代文件名向量时遇到了这个段错误.std :: vector由另一个在相当混乱的代码中读取csv的函数填充.所以我把它缩小到下面的代码导致问题.
向量segfaults的迭代器在产生4个项目的向量的第一个(有时是更晚的)项目之后.推送第5项修复了问题.奇怪?矢量的迭代器工作正常.
#include <iostream>
#include <vector>
using namespace std;
std::vector<int> popbar() {
// populate vector of integers
//
std::vector<int> bar;
for(int i = 1; i < 6; i++)
bar.push_back(i);
return bar;
}
std::vector<std::string> popxar() {
// populate vector of strings
//
std::vector<std::string> xar;
xar.push_back("one");
xar.push_back("two");
xar.push_back("three");
xar.push_back("four");
// this line fixes segfault
//xar.push_back("five");
return xar;
}
void foo () {
// yield next vector item
//
//auto bar = popbar();
auto bar = popxar();
//static auto itx = bar.begin();
static vector<string>::iterator itx = bar.begin();
if (itx == bar.end()) {
cout << "end of line" << endl;
itx = bar.begin();
}
cout << *itx++ << endl;
}
int main() {
for(int i = 0; i < 11; i++) {
foo();
}
}
Run Code Online (Sandbox Code Playgroud)
预期的产出是
one
two
three
four
end of line
one
two
three
four
end of line
one
two
three
Run Code Online (Sandbox Code Playgroud)
我得到的输出是
one
Segmentation fault
Run Code Online (Sandbox Code Playgroud)
也见过
one
two
three
Segmentation fault
Run Code Online (Sandbox Code Playgroud)
和
one
three
three
???1????????????1one1fourSegmentation fault
Run Code Online (Sandbox Code Playgroud)
如果这让它更有趣.可以?请考虑这个也用于矢量.
nne*_*neo 10
您为局部变量定义了一个静态迭代器.你期望会发生什么?
当foo返回时,局部向量xar将会被摧毁,其所有的迭代器无效.重新输入foo会创建一个全新的向量,然后您尝试使用无效的迭代器.随之而来的是未定义的行为.