This question already has an answer here:
- Core dump while loading a file 1 answer
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.
In
list_create
you doThen in
load
you doso now
tmp
is NULL.But later in
load
you dereferencetmp
(e.g. heretmp->next= ....
). So you dereference a NULL pointer which causes your program to crash.