Randy
Randy

Reputation: 97

Infinite while-loop while printing nodes in linkedlist

If I call createnode(x) in main and then follow that with printNodes(); I will get an infinite while-loop that seems to be printing some memory address. I am guessing the issue lies in the fact that i set head = temp?

SinglyLinkedList *head = NULL;

void createNode(int data){
    SinglyLinkedList *temp = malloc(sizeof(SinglyLinkedList));
    temp-> data = data;

    if(head == NULL){
        head = temp;
        return;
    }

    temp->next = head;
    head = temp;
}

void printNodes(){

    SinglyLinkedList *temp = head;

    while ( temp != NULL ){
        printf("%d\r\n",temp->data);
        temp = temp->next;
    }

}

Upvotes: 2

Views: 87

Answers (1)

ikegami
ikegami

Reputation: 385647

SinglyLinkedList *temp = malloc(sizeof(SinglyLinkedList));
temp->data = data;

if(head == NULL){
    head = temp;
    return;
}

temp->next = head;
head = temp;

should be

SinglyLinkedList *temp = malloc(sizeof(SinglyLinkedList));
temp->data = data;
temp->next = head;    // Moved

if(head == NULL){
    head = temp;
    return;
}

head = temp;

which is a very complicate way of writing

SinglyLinkedList *temp = malloc(sizeof(SinglyLinkedList));
temp->data = data;
temp->next = head;
head = temp;

Without this fix, printNodes results in undefined behaviour as a result of the lack of initialization of temp->next.

Upvotes: 3

Related Questions