title: Segmentation fault during insertion of node into linked list
body: <p>I am attempting to alphabetize two separate lists in my add function: one that sorts the nodes by first names, and another that sorts by last names. I also have some logic that checks if a name is already in the list and if it is an error is printed and the list is returned unchanged. Like the title says, I am getting a segmentation fault here and am not sure why. It may be a pretty basic problem but I am new to <code>C</code> and especially new to linked lists.</p>
  
  <p>Here is how the nodes are defined:</p>
  
  <pre><code>typedef struct node {
      char *first;
      char *last;
      long number;
      struct node *nextFirst;
      struct node *nextLast;
  } Node;
  
  typedef struct mlist {
      Node *headFirstName;
      Node *headLastName;
  } MultiLinkedList;
  </code></pre>
  
  <p>And here is my add function:</p>
  
  <pre><code>MultiLinkedList *add(MultiLinkedList *list, char *first, char *last, long num) {
      // allocate a new node
      Node *newNode = malloc ( sizeof(Node) );
      newNode-&gt;first = malloc ( strlen(first) + 1 );
      strcpy(newNode-&gt;first, first);
      newNode-&gt;last = malloc ( strlen(last) + 1 );
      strcpy(newNode-&gt;last, last);
      newNode-&gt;number = num;
      //make placeholder nodes
      Node *a = list-&gt;headFirstName;
      Node *b = list-&gt;headLastName;
      // add this new node at the head of the "byFirst" list
      if (strcmp(newNode-&gt;first, a-&gt;first) &lt; 0) {
              newNode-&gt;nextFirst = list-&gt;headFirstName;
              list-&gt;headFirstName = newNode;
      }
      for (Node *i = list-&gt;headFirstName; i; i = i-&gt;nextFirst) {
              // add after less alphabetical nodes
              if (strcmp(newNode-&gt;first, i-&gt;first) &gt; 0) {
                      newNode-&gt;nextFirst = i-&gt;nextFirst;
                      i-&gt;nextFirst = newNode;
              }
              // return error for duplicate name
              if (strcmp(newNode-&gt;first, i-&gt;first) == 0 &amp;&amp; strcmp(newNode-&gt;last, i-&gt;last) == 0) {
                      printf("That person is already in the list! Please try with a different name.\n");
              }
      }
      // add this new node at the head of the "byLast" list
      if (strcmp(newNode-&gt;last, b-&gt;last) &lt; 0) {
              newNode-&gt;nextLast = list-&gt;headLastName;
              list-&gt;headLastName = newNode;
      }
      for (Node *j = list-&gt;headLastName; j; j = j-&gt;nextLast) {
              // add after less alphabetical nodes
              if (strcmp(newNode-&gt;last, j-&gt;last) &gt; 0) {
                      newNode-&gt;nextLast = j-&gt;nextLast;
                      j-&gt;nextLast = newNode;
              }
      }
      // return the multi-list object with updated or original head pointers
      return list;
  }
  </code></pre>