【发布时间】:2014-11-08 11:33:18
【问题描述】:
我在遍历文件名向量时遇到了这个段错误。 std::vector 由另一个以非常混乱的代码读取 csv 的函数填充。因此,我将其范围缩小到导致问题的以下代码。
在产生具有 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();
}
}
预期的输出是
one
two
three
four
end of line
one
two
three
four
end of line
one
two
three
我得到的输出是
one
Segmentation fault
也见过
one
two
three
Segmentation fault
和
one
three
three
���1������������1one1fourSegmentation fault
如果这使它更有趣。可以?也请考虑这个向量。
【问题讨论】:
-
好像是内存损坏了,能否开启gflags并通过调试器运行
-
只是好奇,您首先将
vector<string>::iterator设为foo()函数中的静态变量的原因是什么? -
我真的很喜欢最后一组输出。非常完美地说明了未定义的行为。
标签: c++ string c++11 vector iterator