0

I'm trying to read the content of a file (containing only integers) into a 2D table, but I get the segmentation fault error at the close statement.

vector<vector<int>> litTableauInt(string nom_fichier, int nb_colonnes) {
    int n;
    int i=0;
    vector<int> colonne(nb_colonnes);
    vector<vector<int>> t(nb_colonnes,vector<int>(1));
    ifstream fichier(nom_fichier);
    while(fichier>>n){
        t[i][0]=n;
        for(int j=1; j<nb_colonnes; j++){
            fichier>>n;
            t[i][j]=n;  
        }
        t.push_back(colonne);
        i++;
    }

    fichier.close();
    return t;
}

I located the error using the gbd command (file file_name, run, bt)

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff74dac01 in __GI___libc_free (mem=0x55555576f1f0) at malloc.c:3123
(gdb) bt
#0  0x00007ffff74dac01 in __GI___libc_free (mem=0x55555576f1f0) at malloc.c:3123
#1  0x00007ffff74c12fe in _IO_new_fclose (fp=0x55555576f1f0) at iofclose.c:77
#2  0x00007ffff7affd98 in std::__basic_file<char>::close() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00007ffff7b3f75b in std::basic_filebuf<char, std::char_traits<char> >::close() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x00007ffff7b418a5 in std::basic_ifstream<char, std::char_traits<char> >::~basic_ifstream() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5  0x00005555555554ef in litTableauInt (nom_fichier="donnees/tonnages_des_dechets_bacs_jaunes.txt", nb_colonnes=13) at dechets-tableau.cpp:24
#6  0x0000555555555614 in testLitTableauInt () at dechets-tableau.cpp:42
#7  0x0000555555556178 in main () at dechets-tableau.cpp:96
coco
  • 1
  • 1
    Will the outer loop (counted with `i`) never be of bounds? Perhaps you should add a check `i < nb_colonnes` at the top of the `while` loop? – Some programmer dude Nov 25 '18 at 16:33
  • Vector `t[i]` has exactly one element - namely, `t[i][0]` - for any value of `i`. Therefore, `t[i][j]` exhibits undefined behavior by way accessing index out of bounds. – Igor Tandetnik Nov 25 '18 at 17:09
  • @johnathan [Usually not a good idea](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – Some programmer dude Nov 25 '18 at 17:46
  • Probably this question might give you some hints on how to do it: [Read file line by line using ifstream in C++](https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c) – yasouser Nov 26 '18 at 20:29

1 Answers1

0

Thank you @Some programmer dude

You put me on the right track, I had inverted the lines and columns when I declared my 2D table (line 5),it should have been :

vector<vector<int>> t(1,vector<int>(nb_colonnes));
coco
  • 1