关闭文件时出现分段错误(核心转储)(C ++)

时间:2018-11-25 16:31:33

标签: c++11

我正在尝试将文件内容(仅包含整数)读入2D表中,但是在close语句中遇到了分段错误错误。

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

我使用gbd命令(文件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

1 个答案:

答案 0 :(得分:0)

谢谢@Some programmer dude

您把我放在正确的轨道上,当我声明2D表(第5行)时,我已经颠倒了行和列,应该是:

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