【发布时间】:2019-10-25 05:35:29
【问题描述】:
我正在尝试创建一个从 .txt 文件加载数据的函数,但是当它运行时,我总是遇到分段错误(核心转储)错误。该文件包含未知数量的行,而每行都有一个字符串和一个由制表符分隔的整数。 list_create 函数只是创建一个数据结构。最后的while循环删除了数据结构,我没有包含代码,因为我确定它不会导致问题但我也想表明我正在释放数据结构。值得一提的是,什么时候使用gdb,我明白了:
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。
#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\n");
abort();
}
else{
while(!feof(fd)&&!ferror(fd)){
fscanf(fd,"%s\t%d\n",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\n");
abort();
}
}
}
tmp->next=NULL;
fclose(fd);
}
int main(int argc,char *argv[]){
list l=list_create();
if(argc!=2){
printf("Input Error\n");
}
load(argv[1],l);
\*Some code*\
while (!list_empty(l)){
list_freenode(list_deletefirst(l));
}
free(l);
return 0;
我希望能够成功加载文件,能够编辑其组件并保存它们。
【问题讨论】:
-
使用调试符号构建程序并在调试器下运行。它会很快告诉您最直接的问题在哪里。除非你是
list_create设法自动挂起足够的节点来包含你的整个文件(这很奇怪),否则根本问题是你永远不会为你的 scanf 分配节点来填充。现在,关于那个调试器...... -
请提供正确(可读)的代码缩进。
-
很高兴看到
list_create的代码。当我们一无所有时,很难说哪里出了问题。其他一些提示:不要将指针隐藏在typedefs后面。在您的情况下,您不必使用malloc(或calloc)在堆上分配struct _list。C(和C++)是NOTjava,您不必在堆上分配所有struct(或class)。另一方面,你所有的struct _node必须(因为你不知道你需要多少)分配给malloc(或类似的)。通常这是在用数据填充列表时完成的(在你的情况下是在阅读时) -
你已经问过同样的问题,还有an answer with 6 upvotes。
标签: c segmentation-fault coredump