[英]C++ std::vector<std::string> iterator segfaults
I encountered this segfault while iterating through a vector of filenames. 我在遍历文件名的向量时遇到了这个段错误。 The std::vector is populated by another function reading csv in a pretty messy code.
std :: vector由另一个在相当混乱的代码中读取csv的函数填充。 So I narrowed it down to the below code causing the problem.
因此,我将其范围缩小到以下导致问题的代码。
The iterator for vector segfaults after yielding first (sometimes later) item of the vector with 4 items. 向量段的迭代器在产生向量的第一个项目(有时是后来的项目)和4个项目之后。 Pushing the 5th item fixes the problem.
推动第5个项目可以解决此问题。 Strange?
奇怪? Iterator for vector works fine.
向量的迭代器工作正常。
#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();
}
}
The expected output is 预期的输出是
one
two
three
four
end of line
one
two
three
four
end of line
one
two
three
The output I get is 我得到的输出是
one
Segmentation fault
also seen 也看到了
one
two
three
Segmentation fault
and 和
one
three
three
���1������������1one1fourSegmentation fault
if that makes it more interesting. 如果这样更有趣。 Does it?
可以? Please consider this for vector as well .
请同时考虑矢量。
You defined a static iterator to a local variable . 您为局部变量定义了一个静态迭代器 。 What did you expect was going to happen?
您预期会发生什么?
When foo
returns, the local vector xar
is going to get destroyed, which invalidates all your iterators. 当
foo
返回时,局部向量xar
将被销毁,这将使所有迭代器失效。 Re-entering foo
creates a brand new vector, and then you try to use an invalid iterator. 重新输入
foo
创建一个全新的向量,然后尝试使用无效的迭代器。 Undefined behaviour ensues. 随后出现未定义的行为。
It's because you have a static
iterator pointing into a non-static local variable. 这是因为您有一个指向非静态局部变量的
static
迭代器。 When the foo
function returns, bar
is destructed. 当
foo
函数返回时, bar
被破坏。 This leads to undefined behavior . 这导致不确定的行为 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.