title: C pointers, inserting elements to HEAD of linked list
body: <p>I am working on a problem in the K&amp;R book (#6.3) where the user inputs a sequence of words, and you have to create a list of these words along with the lines that each one appears on. It's supposed to involve structures so these are the ones I have right now: </p>
  
  <pre><code>struct entry {
      int line; 
      int count; 
      struct entry *next; 
  };
  
  struct word {
      char *str;  
      struct entry *lines; 
      struct word *next; 
  }; 
  
  static struct word *wordlist = NULL;    // GLOBAL WORDLIST
  </code></pre>
  
  <p>However when I input something and the program tries to add a new entry to the structure (which is somewhat like a linked list), there is a problem and the program terminates with no error message. Code for that: </p>
  
  <pre><code>void add_entry(char *word, int line)
  {
      if (word == NULL || line &lt;= 0 || is_blocked_word(word))
          return;
  
      struct word *w; 
      for (w = wordlist; w != NULL &amp;&amp; w-&gt;next != NULL &amp;&amp; !strcmp(w-&gt;str, word); w = w-&gt;next); 
  
      // If word is found in the wordlist, then update the entry
      if (w != NULL) {
          struct entry *v; 
          for (v = w-&gt;lines; v != NULL &amp;&amp; v-&gt;next != NULL &amp;&amp; v-&gt;line != line; v = v-&gt;next); 
  
          if (v == NULL) {
              struct entry *new = (struct entry*) malloc(sizeof(struct entry)); 
              new-&gt;line = line;
              new-&gt;count = 1;
              new-&gt;next = NULL; 
  
              if (w-&gt;lines == NULL)
                  w-&gt;lines = new; 
              else
                  v-&gt;next = new; 
          }
          else v-&gt;count++; 
      }
  
      // If word is not found in the word list, then create a new entry for it
      else {
          struct word *new = (struct word*) malloc(sizeof(struct word)); 
          new-&gt;lines = (struct entry*) malloc(sizeof(struct entry)); 
          new-&gt;next = NULL; 
          new-&gt;str = (char*) malloc(sizeof(char) * strlen(word)); 
          new-&gt;lines-&gt;line = line; 
          new-&gt;lines-&gt;count = 1; 
          new-&gt;lines-&gt;next = NULL; 
          strcpy(new-&gt;str, word); 
  
          // If the word list is empty, then populate head first before populating the "next" entry
          if (wordlist == NULL) 
              wordlist = new; 
          else 
              w-&gt;next = new;
      }
  }
  </code></pre>
  
  <p>The program terminates even after adding just the first word to <code>wordlist</code>. This is on the line that says <code>if (wordlist == NULL) wordlist = new;</code> where <code>new</code> contains the pointer to a valid structure that I malloc'ed. How can this be possible? </p>
  
  <p>As far as I know it's a problem with my pointer usage but I'm not sure where exactly it lies. Can someone help?</p>