Cynthia
Cynthia

Reputation: 25

Double while loop over a linked list causing infinite loop

Subscription *current_sub;
current_sub = sub_user->subscriptions;
while (current_sub != NULL){
    Event *sub_events;
    sub_events = current_sub->calendar->events;
    while (sub_events != NULL){
        add_event(ordered_events, od, sub_events->description, sub_events->time);
        printf("added! \n");
        if(sub_events ->next != NULL){
        sub_events = sub_events->next;
        }
    }
    if (current_sub->next != NULL) {
        current_sub = current_sub->next;
    }
}

So my loop is infinitely looping for some reason and I can't figure out why. both checks for null, and my linked lists should all terminate at some point. Is there something having to do with double while loops checking null pointers that I should be aware about?

EDIT: never mind the infinite loop is fixed. Thanks so much!

Upvotes: 0

Views: 148

Answers (2)

Haris
Haris

Reputation: 12272

You are checking for this condition

while (current_sub != NULL)

And then with an if condition, making sure that if only current_sub->next != NULL then increment current_sub

if (current_sub->next != NULL)

So, the current_sub is never incremented to next when the next points to NULL

Same is the case with the inside while (sub_events != NULL) and the if(sub_events ->next != NULL)

Upvotes: 1

Jim Balter
Jim Balter

Reputation: 16424

if(sub_events ->next != NULL){
    sub_events = sub_events->next;
}

If sub_events ->next is NULL, sub_events won't change, so the next iteration will use the same value, ad infinitum. Same for

if (current_sub->next != NULL) {
    current_sub = current_sub->next;
}

The conditionals make no sense; just remove them and do the assignments unconditionally.

Upvotes: 0

Related Questions