rphello101
rphello101

Reputation: 1771

Printing linked list causes infinite loop (C)?

I have a program that is supposed to load some information from a text file and then display it to the screen. When I display the information, I run into an infinite loop. For the life of me, I can't figure out why (do to my very limited understanding of linked lists and C I'm sure). Here struct:

I saw in someone else's post that the error might have been caused in the load. I figure I'd run into the infinite loop there, but maybe I'm having a problem not setting the last "next" to NULL or something. Here it is:

void loadtimes()
{
    FILE *fileName = fopen("saved_times.txt","r");
    char input[MAX_STR_LEN];
    int counter=1;
    struct PlayerTime *p;

    p=(struct PlayerTime*)malloc(sizeof(struct PlayerTime));

    ...

    if(fileName!=NULL){
        while((fgets(input,MAX_STR_LEN,fileName)!=NULL)){
            if(counter==1){
                p->seconds=atoi(input);
            }
            if(counter==2){
                strcpy(p->name,input);
                counter=0;
                p->next=list_head;
                list_head = p;
            }
            counter++;
        }
    }
}

Hopefully it's something trivial I did wrong. Can anyone help out?

Upvotes: 0

Views: 477

Answers (1)

CS Pei
CS Pei

Reputation: 11047

You only allocate memory for one struct,

 p=(struct PlayerTime*)malloc(sizeof(struct PlayerTime));

you should do this inside the while loop too since you are expecting more list nodes, do you?

Upvotes: 3

Related Questions