Segmentation fault (core dumped) while trying to open a file

倖福魔咒の 提交于 2019-12-24 17:52:19

问题


I am trying to create a program which creates a data structure of people with their names and ids. When I it compiles no problem but when it runs I get segmentation fault(core dumped). The file is on the same folder as the .c file.Also, inside the file the data will be separated by tab. The list_create() function creates the data structure in the form of a list.

I tried instead of making one single line of code with many functions, multiple lines with few functions,use the tmp as a list instead of a node,free variables in a different order but it changed nothing.

#include <stdio.h>
#include <stdlib.h>
#include <assert.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;
};


int list_empty(list l){
        assert(l);
        return l->head==NULL;
}
node list_deletefirst(list l){
        assert(l && l->head);
        node ret;
        l->head=l->head->next;
        l->size--;
        ret->next=NULL;
        return ret;
}

void list_freenode(node n){
        assert(n);
        free(n);
}


void load(char*filename,list l){
    FILE *fd;
    node tmp=l->head;
    if((fd=fopen(filename,"r"))==NULL){
        printf("Error trying to open the file");
                abort();
    }
    else{
                while(!feof(fd)){
                fscanf(fd,"%s\t%d\n",tmp->data.name,&tmp->data.id);

                tmp=tmp->next;
                l->size++;
                }

        }

    tmp->next=NULL;
    fclose(fd);
}

void save(char *filename,list l){
    int i;
    node tmp=l->head;
    FILE *fd;   
    rewind(fd);
    if((fd=fopen(filename,"w"))==NULL){
        printf("File could not be opened");
        abort();
    }
    for(i=0;i<l->size;i++){
        fprintf(fd,"%s\t%.4d\n",tmp->data.name,tmp->data.id);
        tmp=tmp->next;
    }
    rewind(fd);
    fclose(fd);
}

int main(int argc,char *argv[]){
    list l=list_create();
    load(argv[1],l);


    save(argv[1],l);

    while (!list_empty(l)){
                list_freenode(list_deletefirst(l));
        }
    free(l);

    return 0;
}

I expect to get a list with names and ids.


回答1:


free(l->head->next);
l->head=l->head->next;

You are freeing l->head->next and assigning the freed value (garbage) to l->head in the next line.

In consequence you read garbage (segfault) in the second iteration when trying to access to l->head->next.



来源:https://stackoverflow.com/questions/56459467/segmentation-fault-core-dumped-while-trying-to-open-a-file

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