0

I am defining head as a global variable. The user enters integers which should be appended to a singly linked list. I implemented the append function, but it gives me a segmentation fault.

void Append(int x)
{
    struct Node *temp, *current;
    temp = (struct Node*)malloc(sizeof(struct Node));
    temp -> data = x;


    temp -> next = NULL;

    if(head->next ==NULL)
    {
            head = temp;

    }
    else{

            //current = (struct Node*)malloc(sizeof(struct Node));
            current = head;
            while(1)//current != NULL)
            {
                    if(current->next ==NULL)
                    {
                            current =current -> next;
                            printf("added to the end\n");
                            break;
                    }

                    current = current -> next;
            }
    }
}

The main function is given below:

int main()
{
    //create empty List
    head =NULL;

    printf("How many numbers?\n");
    int n,i,x;
    scanf("%d",&n);
    for(i =0; i<n; i++)
    {

            printf("Enter the number\n");
            scanf("%d",&x);
            //Insert(x);
            Append(x);
            Print();
    }
    return 0;
} 
1
  • and change to if(current->next ==NULL){current -> next = temp,; Commented Feb 3, 2014 at 21:50

3 Answers 3

1

you set head to null

head =NULL;

and the next time you access it, you're trying to access one of it's properties

if(head->next ==NULL)

You can't do this, because there is no head->next because head is null

Sign up to request clarification or add additional context in comments.

Comments

0

Since you initialize head to NULL, this line causes an error:

if(head->next ==NULL)

As you are attempting to access member next of a NULL pointer.

To fix this, allocate head before calling Append, or check for head being NULL inside Append.

Comments

0

//Insert(x);=> Enable this and update valid head node. If not in Append() function, if(head->next) should be changed to if(head). That is head pointer must be validated before accessing next..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.