mib1413456 mib1413456 - 2 months ago 8
C Question

Printing singly linked list ends the program abruptly

Here is my code, I am trying to have a program ask the user for some numbers then print them out. I have implemented the use of linked lists for my purpose. The program works but ends abruptly, I have no idea what to add or remove from the code.

#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int item;
struct node *next;
}ListNode;
void printList(ListNode *head);
int main()
{
int n;
ListNode *head = NULL;
ListNode *temp = NULL;
printf("Enter a value: ");
scanf("%d", &n);
while (n != -1)
{
if (head == NULL)
{
head = malloc(sizeof(ListNode));
temp = head;
}
else
{
temp->next = malloc(sizeof(ListNode));
temp = temp->next;
}
temp->item = n;
printf("Enter a value: ");
scanf("%d", &n);
}
while (head != NULL)
{
printf("%i\n", head->item);
head = head->next;
}
free(head);
return 0;
}


When I enter 3 numbes (e.g. 1, 2 and 3), it prints out 123 then ends the program abuptly. Can someone please shed some light on this?

Answer

You do not set the next field of the last element to NULL:

temp->item = n;
temp->next = NULL;  // add this line

And when printing, while (head != NULL) will never hold as there is rubbish in head->next. So then you are trying to access arbitrary pointer which leads to crash.