2013-02-13 1 views
0

사전 파일에서 단어를 읽으려고 시도하고 파일에서 읽는 제 4 줄에 segfault가 표시됩니다. 내가 C++의 벡터에 대해 읽은 것부터 insert 명령을 사용하려면 place holder로 사용할 반복자를 지정해야합니다. 이렇게하려면 내 벡터의 시작 부분에 반복기를 인스턴스화해야합니다. 반복자는 증가 연산자Segfault가 벡터 용량을 예약 한 후에 발생합니다 <string>

it++; 

내가 www.cplusplus.com에 예제 떨어져이를 근거로하고을 사용하여 가리키는 곳 루프 나 증가 제의 내부

vector<string>::iterator it = dictionaryFile.begin(); 

. 이터레이터는 처음 세 줄에서 작동하고 segfault가 발생합니다. getline에 의해 읽혀지는 잘못된 문자가 없는지 확인하기 위해 파일을 두 번 확인했습니다. 이 오류는 벡터 오버플로가 발생하지 않도록 만들기 위해 예약 한 호출과 관련이 있다고 생각합니다.

선언 할 때 새 키워드를 사용하지 않으므로 용량이 5로 제한된 벡터입니까? 그래도 사용중인 새 키워드의 예는 찾을 수 없습니다!

이 오류의 원인이되는 코드 세그먼트를 포함 시켰습니다. 이 segfault를 해결하기 위해이 여러 번 다시 설계했는데 이것이 원래 구현되지 않았습니다. 나는 C++의 마스터가 가질 수있는 통찰력에 감사 할 것입니다. 시간 내 주셔서 감사합니다. 당신의 벡터의 크기는 전류 용량에 도달 (또는 vector::reserve를 호출 할 때, 귀하의 경우, 반복자의 유효 기간 here 섹션 참조) 때

vector<string> dictionaryFile (5, "");                  //Declaration of vector that will hold the words in the dictionary 

ifstream input;                         //Declaration of input file stream 
input.open(inst.c_str()); 

/********************** Test to see if file was opened ********************************/     
if(!input){ 
    cerr << "The file " << inst <<" does not exists in this directory" << '\n'; 
} 
/********************** File is successfully opened**********************************/ 

string temporaryProcessingString = "";                //This string will temporarily hold values read in from the file 
vector<string>::iterator it = dictionaryFile.begin();             //Creates iterator to step through the vector and fix this wild shit 

for(int i = 0; getline(input, temporaryProcessingString); i++){         //See I can follow directions given in class no eof used. 
    cout << "Does this print before SegFault 1 " << endl; 
    if(dictionaryFile.size() >= (dictionaryFile.capacity() - dictionaryFile.size())){  //If current size is greater the 50% capacity reserve size*2 more memory 
     int oldSize; 
     oldSize = dictionaryFile.size(); 
     cout << "Does this print before SegFault 2 " << endl; 
     dictionaryFile.reserve(oldSize + oldSize);             //Reservation new capacity for vector containing dictionary 
    } 

/** this is a test bracket that solely keeps track of the vectors size and capacity in the terminal COMMENT OUT BEFORE SUBMITTING*/ 
cout << "________________________________________________" << '\n'; 
cout << "Loop Run: " << i << endl; 
cout << "Size: " << dictionaryFile.size() << ", Capacity: " << dictionaryFile.capacity() << endl; 
cout << "________________________________________________" << '\n'; 
dictionaryFile.insert(it, temporaryProcessingString); /*******************************THIS LINE CAUSES THE SEGFAULT! UNFORTUNATELY IT IS ALSO THE LINE THAT MOVES THE DATA INTO THE VECTOR************************/ 
it++; 
cout << "Dictionary Entry: " << dictionaryFile[i] << endl; 

} 
cout << "Dictionary Entry Primary Test: " << dictionaryFile[0] << endl; 
+0

나는 한 마디 만 말하고 싶다. 한 마디. [Valgrind] (http://valgrind.org/). – zwol

+0

크기 증가에 부딪 칠 때 "oldSize"를 출력하는 것은 어떻습니까? –

+0

벡터의 크기를 다시 할당 할 때 반복기가 유효하지 않게되는 것을 확신합니다. 할당이 "제자리에서"확장 될 수 있기 때문에 첫 번째 또는 두 번째 발생하지 않을 수 있지만 조만간 유효하지 않게됩니다. –

답변

6

, 내부 알고리즘을 다시 할당하고 잠재적으로 다른 곳으로 이동합니다 벡터의 요소에 대한 모든 반복기를 유효하지 않게 만듭니다.

프로그램이 끝에 삽입하는 것처럼 보이므로 vector::insert 대신 vector::push_back을 사용하십시오. 그런 다음 reserve을 건너 뛸 수 있습니다. 내부 알고리즘은 매우 뛰어납니다 (새 요소 하나 하나씩 재배치하는 것을 두려워 할 필요가 없습니다. 알고리즘은 그보다 똑똑합니다).

관련 문제