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.