crazyaboutliv
crazyaboutliv

Reputation: 3199

Appending a List--Segmentation fault

I am trying to append one list with another . If i pass a pointer-to-the-pointer of both the lists and just display them, then , the code works fine. But if i use code to reach the NULL pointer of the first list and then equate it to the first one of the second, then it gives a segmentation fault. Please let me know what the mistake is. Code is below :

#include<stdio.h>
#include<stdlib.h>
struct node 
{
    int data;
    struct node* next;
}*Head,*New;
void display(struct node **p)
{
    struct node *curptr;
    curptr=*p;
    if(curptr==NULL)
        printf("list is empty");
    else
    {
        while(curptr)
        {
            printf("->%d",curptr->data);
            curptr=curptr->next;
        }
    }
}
void combine(struct node **a,struct node **b)
{
    //display(&(*a));
    struct node *aptr;
    aptr=*a;
    while(aptr)
        aptr=aptr->next;
    aptr->next=*b;
    *b=NULL;
    display(&(*a));

    //display(&(*a));
    //display(&(*b));   

}
void main()
{
    Head=NULL;
    New=NULL;
    int choice;
    while(1)
    {
          case 9:
        {
            printf("Combining two lists");
            combine(&Head,&New);
            break;
        }

Upvotes: 1

Views: 137

Answers (2)

codaddict
codaddict

Reputation: 454920

The problem is here:

while(aptr)
    aptr=aptr->next;
aptr->next=*b

When you break out of the while loop aptr will be NULL next when you try to do aptr->next you get the SEGV.

To fix this break out of the loop when you reach the last node(aptr->next will be NULL) rather than aptr becoming NULL.

Something on these line:

// if fist list does not exist.
if(*a == NULL) {
        *a = *b;
        return;
}

struct node *aptr;
aptr=*a;

// loop till you reach the last node of fist list.
while(aptr->next)
        aptr=aptr->next;

// append.
aptr->next=*b;
*b=NULL; 

Upvotes: 5

manol
manol

Reputation: 582

while(aptr)
  aptr=aptr->next;

runs till aptr is NULL, after that

aptr->next=*b;

causes a segmentation fault since you dereference NULL.

Upvotes: 2

Related Questions