2

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;
    }

}
Randy
  • 87
  • 6
  • 2
    You only give a value to `temp->next` when `head` is not NULL. To be correct, the code must always set `temp->next`. The easy way to do that is to remove the whole `if` statement. – user3386109 Jan 12 '22 at 06:16
  • 2
    Try using `calloc` instead? – Zoso Jan 12 '22 at 06:18
  • 1
    @user3386109 I totally forgot that I didn't set `temp->next`, it fixed the problem instantly.. thanks! :) – Randy Jan 12 '22 at 06:23
  • 2
    next time please make sure you add the *complete* code (including the definition of `SingleLinkedList` and a minimal `main`). – OrenIshShalom Jan 12 '22 at 06:28
  • Does this answer your question? [Difference between malloc and calloc?](https://stackoverflow.com/questions/1538420/difference-between-malloc-and-calloc) – OrenIshShalom Jan 12 '22 at 06:38

1 Answers1

3
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.

ikegami
  • 367,544
  • 15
  • 269
  • 518