Insert a string into a linked list

I'm trying to write a program that takes a sentence from user input and stores that in a linked list. This is what I have done so far and it seems to be working except that when I print the list it prints the string and then goes into a infinite loop printing "garbage". Can you see where I have gone wrong?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STRLENGTH 100

typedef struct node {
   char data;
   struct node *next;
} node;

int
main(void) {
   char str[STRLENGTH];
   printf("Enter a string: ");
   gets(str);

   node *linkedList = NULL;
   node *head = NULL;
   node *pre = NULL;

   int i;
   for(i = 0; str[i] != '\0'; i++) {
      linkedList = malloc(sizeof(node));
      if(str[i] == ' ')
         linkedList -> data = 0;
      else
         linkedList -> data = str[i];

      if(pre != NULL)
         pre -> next = linkedList;
      else
         head = linkedList;
      pre = linkedList;
   }

   while(head != NULL) {
      printf("%c", head -> data);
      head = head -> next;
   }

   return 0;
}

Upvotes: 0

Views: 12905

Answers (2)

JustinDanielson
JustinDanielson

Reputation: 3185

Your bug only occurs in the final iteration of the for-loop. You're not initialize the next pointer of the final element in the linkedList.

If you want to minimize the number of operations you're doing. After the execution of the for-loop and before the while-loop add

pre->next = NULL;

Since you know pre is going to point to the final node. This way, you won't do it every iteration of the loop.

Upvotes: 0

Kninnug
Kninnug

Reputation: 8053

You forgot to initialize linkedList -> next, so it has a garbage value, which is not necessarily NULL. Therefore the while loop tries to follow it and accesses some random memory address (pointed to by head -> next) and causes undefined behaviour.

In addendum, don't use gets, it doesn't protect against overflow. Use fgets instead.

Upvotes: 2

Related Questions