c++11 - 关闭文件时出现分段错误(核心转储)(C++)
问题描述
我正在尝试将文件的内容(仅包含整数)读入 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
解决方案
你让我走上了正确的道路,当我声明我的二维表(第 5 行)时,我已经颠倒了行和列,它应该是:
vector<vector<int>> t(1,vector<int>(nb_colonnes));
推荐阅读
- python-3.x - 如何在python中删除数据框中的初始行
- ansible - 在运行时指定主机凭据 Ansible
- python - 当我尝试为 scikit-learn 模型拟合另外 1 个功能时,出现此错误“ValueError:找到样本数量不一致的输入变量”
- lisp - (defun defun() 3) 会做什么?
- python - 为什么我做的函数给了我一个 None 类型?
- c++ - 从整个 std::string 中删除特定字符
- django - 如何将 .env 文件放入远程主机服务器
- encoding - utf-8 和 ascii 的前 128 个字符是否相同?
- laravel-5 - Laravel 表单请求验证问题
- javascript - 导入 firebase.firestore() 返回未定义