cdata-structureslinked-listqueuefeof

Queues Using Linked List in C only take last node as a whole infinite queue


I am working on a data structure project. I am asked to take information from a file called "ToServe.txt". The data in the file is in the form:

TicketNumberSpaceStudentIDSpaceStudentName
TicketNumberSpaceStudentIDSpaceStudentName

However, implementing the two functions below, I only get the last student infinite times in my queue

int Start(advisee** front, advisee** rear) {
  advisee* student, *walker;
  FILE* infp;
  student = (advisee*)malloc(sizeof(advisee));
  infp = fopen("ToServe.txt", "r");
  if(infp == NULL) {
    return 0;
  }
  while(!feof(infp)) {
    fscanf(infp, "%d", &student->ticket);
    fscanf(infp, "%d", &student->ID);
    fgets(student->name, 100, infp);
    student->next = NULL;
    enqueue(front, rear, student);
  }
  walker = *front;
  fclose(infp);
  return 1;
}
void enqueue(advisee** front, advisee** rear, advisee* ToAdd) {
    if (*front == NULL)
      *front = ToAdd;
    else
      (*rear)->next = ToAdd;
    *rear = ToAdd;
}

Solution

  • There is only one item allocated:

    advisee* student = (advisee*)malloc(sizeof(advisee));
    

    ...and the loop just keeps mutating that single advisee and repeatedly adds the same pointer to the queue. So the queue ends up with pointers to one single advisee.

    The solution is to move the allocation inside the loop.