Reputation: 6750
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
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.Upvotes: 2