So this is a very simple program to create and display a linked list. Here I'm getting caught in the display loop, and I'm seeing infinite '2->2->2->...' on screen.
After debugging, I can see that my program ALWAYS goes into the if statement of insertNode() whereas it should only go there ONCE i.e. when the linked list is initialized.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * next;
};
struct node * head = NULL;
struct node * curr = NULL;
void insertNode(struct node * temp2) {
if (head == NULL) {
head = temp2;
head->next = NULL;
}
else {
temp2->next = head;
head = temp2;
}
}
void display() {
curr = head;
while (curr->next != NULL)
{
printf("%d->",curr->data);
curr = curr->next;
}
}
void main() {
struct node * temp = (struct node *) malloc (sizeof(struct node));
temp->data = 5;
insertNode(temp);
temp->data = 6;
insertNode(temp);
temp->data = 1;
insertNode(temp);
temp->data = 2;
insertNode(temp);
display();
}
currinside of display instead of polluting the global area if you only use it in there. try to avoid globals as much as possible.displayso thatheadreally points to something before dereferencing it.