title: Segmentation fault in a C function to concatenate two linked lists
body: <p>I am trying to write a function that concatenates two lists to form a new list containing copies of all the nodes in list1 and list2, and returns a pointer to this new list.</p>
  
  <pre><code>Node *concat(Node *list1, Node *list2) {
    Node *head, *ptr;
    if (list1==NULL) {
      if (list2!=NULL)
        return copy(list2); 
  /*copy refers to a function that copies a list &amp; returns pointer to new list*/
      else
        return NULL;
    }
    else if (list2==NULL) {
      if (list1!=NULL)
        return copy(list1);
      else
        return NULL;
    }
    else {
    while (list1 != NULL) {
      if (head==NULL) {
        head=newNode(list1-&gt;airport);
        ptr=head;
      }
      else {
        Node *n=newNode(list1-&gt;airport);
        ptr-&gt;next=n;
        ptr=ptr-&gt;next;
      }
      list1=list1-&gt;next; }
    while (list2 != NULL) {
      Node *n1=newNode(list2-&gt;airport);
      ptr-&gt;next=n1;
      ptr=ptr-&gt;next;
      list2=list2-&gt;next;
    }
    }
    return head;
  }
  </code></pre>
  
  <p>When I test this function using a program that prints </p>
  
  <ul>
  <li>a one-node list1 concatenated to a NULL list2</li>
  <li>a NULL list1 concatenated to a one-node list2</li>
  <li>a list of nodes (list1) concatenated to a one-node list2</li>
  </ul>
  
  <p>I get a segmentation fault.</p>
  
  <p>I can't find the source of the segmentation of fault in the function, although I believe it is in the first portion, before <code>while (list1 != NULL)</code> , because it seems to work if neither of the lists are NULL.</p>