简体   繁体   中英

segmentation fault (core dumped) when closing file (c++)

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

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM