Reputation: 3
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.
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 & 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->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 I test this function using a program that prints
I get a segmentation fault.
I can't find the source of the segmentation of fault in the function, although I believe it is in the first portion, before while (list1 != NULL)
, because it seems to work if neither of the lists are NULL.
Upvotes: 0
Views: 683
Reputation: 26
Can't add much to the comments and answer you've received already, but have put comments in your code to aid your understanding of why it crashes.
Node *concat(Node *list1, Node *list2) {
/* These are uninitialised variables, which basically means they will
* take the whatever random values that are on the stack. It is unlikely
* that the values will be NULL.
*/
Node *head, *ptr;
if (list1==NULL) {
if (list2!=NULL)
return copy(list2);
/*copy refers to a function that copies a list & 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) {
/* When you get here, head isn't NULL so you go to the else block */
if (head==NULL) {
head=newNode(list1->airport);
ptr=head;
}
else {
Node *n=newNode(list1->airport);
/* Bang! Highly likely to crash here, as you are dereferencing a
* random value (in ptr) as though it is a 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;
}
Upvotes: 0
Reputation: 344
Since you already have a copy function which creates new list and returns head points so program can be modified as below (if NULL input is passed to a copy function it should return NULL, this assumption is made)
Node *concat(Node *list1, Node *list2) {
Node *head = NULL, *ptr = NULL;
if(list1 != NULL)
{
head = copy(list1);
}
if(list2 != NULL)
{
if(NULL == head)
{
return copy(list2);
}
}
ptr = head;
while(ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = copy(list2);
return head;
}
Upvotes: 0