Walter
Walter

Reputation: 1

segmentation fault while reading file into linked list

In the below given code, im not able to print the content of a student.txt file. I'm not sure if my add function is not malloc 'ing the contents properly. Any suggestions in my code.

My struct

typedef struct student{
  char *name;
  char *number;
  struct student *previous;
  struct student *next;
}Student;

main.c

int main (int argc, char **argv) {
  FILE *in = fopen("student.txt", "r");
  char name[20];
  char num[20];
  Student *list=NULL;

  /* read file into single linked list */
 while(fscanf(in, "%s %s",name, num)==2) {
        list = add(list,name, num);
 }

  /* print the list */
  printf ("\n\nOriginal list\n********************\n");
  print (list);

list.c

Student * add (Student *list, char *name, char *number) {
Student *node = malloc(sizeof(Student));
node->name = strdup(128);

Student *current, *head;
void print (Student *list) {
for(current = head; current ; current=current->next){
                printf("%s", current->name);
}
}

node->number = strdup(8);
if(head==NULL){
current = head = node;
} else {
current = current->next = node;
}
        return list;
}

student.txt

John 123 
Walter 456
Selena 789

Upvotes: 0

Views: 52

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409364

The problem is very likely the call to strdup:

strdup(128);

The argument to the strdup function is the string to duplicate. This should be a pointer to the first character in a null-terminated string.

You tell strdup that this pointer is 128 which is usually an invalid address, leading to undefined behavior and your crash.

You should be passing name instead:

strdup(name);

You seem to be making this mistake(?) for number as well.

Upvotes: 1

Related Questions