Rivasa
Rivasa

Reputation: 6750

Linked list is throwing an infinite loop, yet latest pointer is set to null

I've written a linked list and when I'm doing the append to end, it seems to be going into an infinite loop.

// this function will make a node and give it a value at the end of the list
void add_at_end(struct Node* begin, int v) {
    // new node
    struct Node* temporary = begin; // pointer to start of list
    temporary->vv = v;
    temporary->nx = NULL; // latest node
    if (begin == NULL) { // this will make a new list if it is empty
        begin = temporary;
        return;
    }
    struct Node* iterate = begin;
    while (iterate->nx != NULL) { iterate = iterate->nx; }
    iterate->nx = temporary;
    return;
}

I call it using:

struct Node alpha;
add_at_end(&alpha, 1);

Why is this throwing an infinite loop?

Upvotes: 0

Views: 54

Answers (1)

Karoly Horvath
Karoly Horvath

Reputation: 96286

  • alpha is not initalized, it contains garbage, including the next pointer. Access the content is undefined behaviour, which could result in an infinite loop... or crash.. or whatever.
  • begin = temporary; this will set the variable in the local scope, and won't have any effect on what you've passed to the function. You could either pass a pointer to the pointer (**), or pass an existing node to the function (in which case there's no need to check). You are doing a mix of these which doesn't make sense.
  • It's very inefficient to traverse the whole list just to add an element. You should maintain a link to the last node, so that it becomes an O(1) operation.

Upvotes: 2

Related Questions