首页 > 解决方案 > 加载文件时的核心转储

问题描述

我正在尝试创建一个从 .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;

我期待成功加载文件,能够编辑其组件并保存它们。

标签: csegmentation-faultcoredump

解决方案


您的分段错误可能是由于您的函数list_create()分配了一个数据结构,但您的函数load()填充的数据结构与文件中的行一样多,因此将数据写入未分配的空间。


推荐阅读