2015-11-22 2 views
0

Я получаю эту странную ошибку. Только в linux, который мне нужен, чтобы он работал на этой ОС, но на окнах работает отлично.Получение Segfault при закрытии файла

Выполняется только по inFile.close(); Протестировано с большим количеством сообщений cout.

Вот функция, в которой происходит сбой. (. Element300 по переменному стилю строка, которая состоит из 81 символов, включая терминатор Кроме того, файл читается в этом JAVA ключевых слов, чтобы ничего не более 80 символов.)

Вот функция:

void HT300::fill300() 
{ 
    Element300 readLine = "\0"; 
    Element300 tempLine = "\0"; 
    int hashedValue; 
    int tempIndex = 0; 
    int tempProbed = 0; 
    int tempLineIndex = 0; 
    int readLineIndex = 0; 
    ifstream inFile; 

    inFile.open("RWJAVA.DAT"); 

    if(!inFile) 
    { 
     cerr << "File not found: RWJAVA.DAT" << endl; 
    } 
    else 
    { 
     while(!inFile.getline(readLine,MAX_SIZE,'\n').eof()) 
     { 
      while(readLine[readLineIndex] == ' ') 
      { 
       readLineIndex++; 
      } 
      while(isalnum(readLine[readLineIndex])) 
      { 
       tempLine[tempLineIndex] = readLine[readLineIndex]; 
       tempLineIndex++; 
       readLineIndex++; 
      } 
      tempLine[tempLineIndex] = '\0'; 


      hashedValue = hash300(tempLine); 
      tempIndex = hashedValue; 

      while(strcmp(theTable[tempIndex].reserved,tempLine) != 0 && strcmp(theTable[tempIndex].reserved, "\0") != 0) 
      { 
       tempProbed++; 
       tempIndex += 3; 

       if(tempIndex > MAX_TABLE) 
       { 
        tempIndex = 0; 
       } 

      } 
      if(strcmp(theTable[tempIndex].reserved,"\0") == 0) 
      { 
       strcpy(theTable[tempIndex].reserved,tempLine); 
       theTable[tempIndex].probed = tempProbed; 
       theTable[tempIndex].hashed = hashedValue; 
      } 

      tempIndex = 0; 
      tempProbed = 0; 
      tempLineIndex = 0; 
      readLineIndex = 0; 
      strcpy(tempLine, "\0"); 


     } 

    } 
    inFile.close(); 
    return; 
} 

входной_файл ошибка ОКНА:

Multiple errors reported. 

1) Failed to execute MI command: 
-var-create - * inFile 
Error message from debugger back end: 
-var-create: unable to create variable object 

2) Failed to execute MI command: 
-var-create - * inFile 
Error message from debugger back end: 
-var-create: unable to create variable object 

3) Failed to execute MI command: 
-data-evaluate-expression inFile 
Error message from debugger back end: 
No symbol "inFile" in current context. 

4) Failed to execute MI command: 
-var-create - * inFile 
Error message from debugger back end: 
-var-create: unable to create variable object 

5) Unable to create variable object 
+0

Я еще не читал ваш код, но вы, вероятно, пишете вне своих массивов и коррумпируете структуры данных для 'infile' или сами портируете объект' ifstream inFile'. С помощью отладчика настройте сторожевую точку на значение 'inFile'. Если он изменяется в строке кода, который не должен касаться его (например, в строке, которая записывает массив), вы обнаружите ошибку. (Или, по крайней мере, последствие. Фактическая ошибка может быть раньше и нарушать предположения, которые делает код позже). –

+0

Будет ли эта проблема зависящей от системы? Пример, как я сказал в оригинальном вопросе: работает в Windows 10, Eclipse IDE, но не в Linux. @PeterCordes – Programmer12432

+0

Не обязательно, чтобы проблема возникла в инструкции 'close'. Вероятно, это происходит где-то в другом месте, где ваша память ссылается на выделенную область. Что такое 'Element300'? Правильно ли считываются данные? – unxnut

ответ

1

петля:

while(strcmp(theTable[tempIndex].reserved,tempLine) != 0 && strcmp(theTable[tempIndex].reserved, "\0") != 0) 
      { 
       tempProbed++; 
       tempIndex += 3; 

       if(tempIndex > MAX_TABLE) 
       { 
        tempIndex = 0; 
       } 

      } 

Был someh ow выходит за пределы. Я исправил это, изменив проверяемые условия, а также установив оператор if на >= вместо >.

Смежные вопросы