2015-05-01 1 views
0

Я получаю странный segfault, которого я не понимаю.Seg Fault на cin. Пробовал дело. Lousy at gdb

[email protected] ~/code/byun-sp15 $ g++ -g all_pairs.cpp 
[email protected] ~/code/byun-sp15 $ ./a.out 
Please enter filename: 
table.txt 
Segmentation fault 

Как вы можете видеть из COUT staements, он segfaulting прямо в cin>>filename; Вот основная функция:

#include <iostream> 
#include <fstream> 
#include <vector> 
#include <sstream> 

using std::cin; 
using std::cout; 
using std::endl; 
using std::string; 
using std::ifstream; 
using std::vector; 

int main() 
{ 
     int n; 

     string filename; 
     cout << "Please enter filename: " << endl; 
     cin >> filename; 
     cout << "FLAG FLAG FLAG"; 

     ifstream fin(filename.c_str()); 
     if (!fin.is_open()) { 
       cout << "ERROR: file not found. Exiting..." << endl; 
       return -1; 
     } 

     fin >> n; 
     vector<Table> tables; 
     int temp; 
     for (int i = 0; i < n; i++) { 
       for (int j = 0; j < n; j++) { 
         fin >> temp; 
         tables[0].data[i][j] = temp; 
       } 
     } 

     for (int i = 1; i < n-1; i++) { 
       tables.push_back(calc_next_table(tables, i, n)); 
     } 

     return 0; 
} 

Я действительно чувствую себя идиоткой, я никогда не встречал этого раньше. Я нашел this, но это не решило. Я даже попробовал GDB (который я не знаю, как использовать), и все, что я получил это:

Program received signal SIGSEGV, Segmentation fault. 
0x0000000000401ae8 in std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >::operator[] (this=0x0, __n=0) at /usr/include/c++/4.8/bits/stl_vector.h:771 
771  { return *(this->_M_impl._M_start + __n); } 
(gdb) list 
766  * out_of_range lookups are not defined. (For checked lookups 
767  * see at().) 
768  */ 
769  reference 
770  operator[](size_type __n) 
771  { return *(this->_M_impl._M_start + __n); } 
772 
773  /** 
774  * @brief Subscript access to the data contained in the %vector. 
775  * @param __n The index of the element for which data should be 

Это выглядит как вектор делает что-то в стиле фанк, но я даже не объявил свои векторы еще ! Есть идеи?

EDIT: Я хотел ответ @ Нелсон, но следующий по-прежнему бросает Segfault:

 fin >> n; 
     vector<Table> tables; 
     Table t; 
     tables.push_back(t); 

     int temp; 
     for (int i = 0; i < n; i++) { 
       for (int j = 0; j < n; j++) { 
         fin >> temp; 
         tables[0].data[i][j] = temp; 
       } 
     } 

     cout << "FLAG FLAG FLAG" << endl; 

Таблица содержит один элемент, а vector<vector<int>> под названием data. Должен ли я опубликовать это также?

+1

Что делать, если вы изменяете 'cout <<" FLAG FLAG FLAG ",' to 'cout <<" FLAG FLAG FLAG "<< endl;'? Обычно (по какой-то причине) он фактически ничего не печатает до конца строки. – immibis

+0

отлично, что получил меня прошлым cin noow im на фактический segfault – Will

ответ

3

Я думаю, что проблема здесь:

fin >> n; 
    vector<Table> tables; 
    int temp; 
    for (int i = 0; i < n; i++) { 
      for (int j = 0; j < n; j++) { 
        fin >> temp; 
        tables[0].data[i][j] = temp; // HERE 
      } 
    } 

вектор пуст, пока вы к нему доступ.

ли

tables.push_back(..something..) 

первым. Как это:

fin >> n; 
    vector<Table> tables; 
    Table someTable;    // Create a table 
    tables.push_back(someTable); // Put it in the vector 
    int temp; 
    for (int i = 0; i < n; i++) { 
      for (int j = 0; j < n; j++) { 
        fin >> temp; 
        tables[0].data[i][j] = temp; 
      } 
    } 

EDIT:

Так вы говорите, что в таблице также есть вектор, то вам нужно изменить:

    tables[0].data[i][j] = temp; 

использовать push_back также.

Вы не можете получить доступ к элементам в векторе, если вы не добавили элементы в первую очередь.

Если таблица имеет элемент:

vector<vector<int>> data; 

вы могли бы, возможно, сделать что-то вроде:

fin >> n; 
    vector<Table> tables; 
    Table someTable;    // Create a table 
    tables.push_back(someTable); // Put it in the vector 
    int temp; 
    for (int i = 0; i < n; i++) { 
      tables[0].data.push_back(vector<int>()); // create the i'th vector and insert it 
      for (int j = 0; j < n; j++) { 
        fin >> temp; 
        tables[0].data[i].push_back(temp); // Use push_back 
      } 
    } 

Примечание: Я не проверял это, как я не рядом с компилятором ... но я думаю, что что-то в этом роде.

+0

Отлично! Большое спасибо, его ломают позже, где я ожидал этого сейчас! – Will