title: Insert a string into a linked list
body: <p>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?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  #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 -&gt; data = 0;
        else
           linkedList -&gt; data = str[i];
  
        if(pre != NULL)
           pre -&gt; next = linkedList;
        else
           head = linkedList;
        pre = linkedList;
     }
  
     while(head != NULL) {
        printf("%c", head -&gt; data);
        head = head -&gt; next;
     }
  
     return 0;
  }
  </code></pre>