Segmentation fault in a C function to concatenate two linked lists -


i trying write function concatenates 2 lists form new list containing copies of nodes in list1 , list2, , returns pointer new list.

node *concat(node *list1, node *list2) {   node *head, *ptr;   if (list1==null) {     if (list2!=null)       return copy(list2);  /*copy refers function copies list & returns pointer 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->airport);       ptr=head;     }     else {       node *n=newnode(list1->airport);       ptr->next=n;       ptr=ptr->next;     }     list1=list1->next; }   while (list2 != null) {     node *n1=newnode(list2->airport);     ptr->next=n1;     ptr=ptr->next;     list2=list2->next;   }   }   return head; } 

when test function using program prints

  • a one-node list1 concatenated null list2
  • a null list1 concatenated one-node list2
  • a list of nodes (list1) concatenated one-node list2

i segmentation fault.

i can't find source of segmentation of fault in function, although believe in first portion, before while (list1 != null) , because seems work if neither of lists null.

can't add comments , answer you've received already, have put comments in code aid understanding of why crashes.

node *concat(node *list1, node *list2) {  /* these uninitialised variables, means   * take whatever random values on stack. unlikely  * values null.  */ node *head, *ptr;    if (list1==null) {   if (list2!=null)     return copy(list2);      /*copy refers function copies list & returns pointer new list*/   else     return null; } else if (list2==null) {   if (list1!=null)     return copy(list1);   else     return null; } else { while (list1 != null) {  /* when here, head isn't null go else block */  if (head==null) {   head=newnode(list1->airport);   ptr=head; } else {   node *n=newnode(list1->airport);    /* bang! highly crash here, dereferencing     * random value (in ptr) though valid pointer.     */   ptr->next=n;   ptr=ptr->next; } list1=list1->next;  } while (list2 != null) {   node *n1=newnode(list2->airport);   ptr->next=n1;   ptr=ptr->next;   list2=list2->next; } } return head; } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -