加载文件时的核心转储 [英] Core dump while loading a file
问题描述
我正在尝试创建一个从 .txt 文件加载数据的函数,但是当它运行时,我总是遇到分段错误(核心转储)错误.该文件包含未知数量的行,而每行都有一个字符串和一个由制表符分隔的整数. list_create 函数只是创建一个数据结构.最后的while循环删除了数据结构,我没有包含代码,因为我确定它不会导致问题但我也想表明我正在释放数据结构.值得一提的是,什么时候使用gdb,我明白了:
I am trying to create a function which loads data from a .txt file but when it runs I always get a segmentation fault(core dumped) error. The file contains an unknown number of lines while each line has a string and an integer separated by tab.The list_create function just creates a data structure. The while loop in the end deletes the data structure, I did not include the code because I am sure it does not cause the problem but I also want show that I am freeing the data structure.It is worth mentioning that when is gdb used, I get:
Program received signal SIGSEGV, Segmentation fault.
0x0000555555554c46 in load (filename=0x7fffffffe2ab "students.txt",
l=0x555555757260) at Student.c:92
92 tmp->next=malloc(sizeof(struct _node));
我试图用别的东西改变 feof,使用和不使用 ferror 并将 fopen 的模式更改为 r 而不是 a.
I have tried to change the feof with something else,use with and without ferror and change the mode for fopen to r instead of a.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#define MAXSTRING 50
typedef struct{
char name[MAXSTRING];
int id;
} student;
typedef struct _node* node;
typedef struct _list* list;
struct _node {
student data;
node next;
};
struct _list {
node head;
int size;
};
list list_create(){
list l=(list) malloc(sizeof(struct _list));
assert(1);
l->head=NULL;
l->size=0;
return l;
}
void load(char*filename,list l){
FILE *fd=fopen(filename,"r");
node tmp=l->head;
if(fd==NULL){
printf("Error trying to open the file
");
abort();
}
else{
while(!feof(fd)&&!ferror(fd)){
fscanf(fd,"%s %d
",tmp->data.name,&tmp->data.id);
tmp->next=(node)malloc(sizeof(struct _node));
assert(tmp->next);
tmp=tmp->next;
l->size++;
if (tmp==NULL){
printf("Error trying to allocate memory
");
abort();
}
}
}
tmp->next=NULL;
fclose(fd);
}
int main(int argc,char *argv[]){
list l=list_create();
if(argc!=2){
printf("Input Error
");
}
load(argv[1],l);
*Some code*
while (!list_empty(l)){
list_freenode(list_deletefirst(l));
}
free(l);
return 0;
我希望能够成功加载文件,能够编辑其组件并保存它们.
I am expecting to load the file successfully, be able to edit its components and save them.
推荐答案
你的分段错误可能是因为你的函数 list_create()
分配了一个数据结构,但是你的函数 load()
填充与文件中的行一样多的数据结构,从而将数据写入未分配的空间.
Your segmentation fault may be explained by the fact that your function list_create()
allocates one data structure, but your function load()
populates as many data structures as lines in the file, thus writing data in unallocated space.
这篇关于加载文件时的核心转储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!