segmentation fault (core dump) while loading a file [duplicate]

假如想象 提交于 2019-12-25 02:47:36

问题


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

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

I am expecting to load the file successfully, be able to edit its components and save them.


回答1:


In list_create you do

l->head=NULL;

Then in loadyou do

node tmp=l->head;

so now tmp is NULL.

But later in load you dereference tmp (e.g. here tmp->next= ....). So you dereference a NULL pointer which causes your program to crash.



来源:https://stackoverflow.com/questions/56563850/segmentation-fault-core-dump-while-loading-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!