파일 이름의 벡터를 반복하는 동안이 segfault가 발생했습니다. std :: vector는 꽤 복잡한 코드에서 csv를 읽는 또 다른 함수로 채워집니다. 그래서 나는 문제를 일으키는 아래의 코드로 그것을 좁혔다.C++ std :: vector <std::string> 반복자 segfaults
벡터의 반복자는 4 개의 항목이있는 벡터 항목을 처음 (때로는 나중에) 생성 한 후에 세분합니다. 다섯 번째 항목을 누르면 문제가 해결됩니다. 이상한? 벡터에 대한 반복자가 정상적으로 작동합니다.
#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
two
three
Segmentation fault
및
을 볼one
Segmentation fault
입니다
one
three
three
���1������������1one1fourSegmentation fault
더 흥미로운 부분이 있다면. 그거야? 벡터에 대해서도이 점을 고려하십시오.
메모리 손상이있는 것처럼 보입니다. gflags를 활성화하고 디버거를 통해 실행할 수 있습니까? – radar
'벡터 :: iterator'를'foo()'함수의 정적 변수로 만드는 이유는 무엇입니까? 처음? –
나는 최종 결과물을 정말 좋아한다. 정의되지 않은 동작을 아주 완벽하게 보여줍니다. – nneonneo