0

I am trying to create the program to build the linked list but its giving me a segmentation fault while creating the second fault.

[root@vm c_prog]# vi link1.c

#include <stdio.h>
#include <stdlib.h>


struct node {

        int x;
        struct node *next;
        };

int main () {

        int d;
        struct node *root;
        struct node *current;



        root = malloc(sizeof(struct node));

        current = root;

        printf ("Location of root is %p \n", root);

d = 1;
while (d>0){

        printf ("Enter the value of X: ");
        scanf ("%d", &current->x);

        printf ("value of x is stored\n");
        printf ("Location of current is %p \n", current);
        printf ("Value of X in 1st node: %d\n", current->x);

        current = current->next;


        printf ("Enter zero to terminate the loop: ");

        scanf ("%d",&d);

        }

}

[root@vm c_prog]# ./a.out 
Location of root is 0xc34b010 
Enter the value of X: 3
value of x is stored
Location of current is 0xc34b010 
Value of X in 1st node: 3
Enter zero to terminate the loop: 5
Enter the value of X: 5
Segmentation fault
[root@vm c_prog]# 

2 Answers 2

5

You never initialise next so the line

current = current->next;

changes current to point to uninitialised memory. You also need to allocate a new node for every iteration of your loop.

The following code should be close to working. (It could be simplified; I've tried to keep it as close as possible to your code.)

int main () {
    int d;
    struct node *root = NULL;
    struct node *current;
    d = 1;
    while (d>0){
        printf ("Enter the value of X: ");
        scanf ("%d", &d);
        if (root == NULL) {
            root = calloc(1, sizeof(struct node));
            current = root;
            printf ("Location of root is %p \n", root);
        }
        else {
            current->next = calloc(1, sizeof(struct node));
            current = current->next;
        }
        current->x = d;

        printf ("value of x is stored\n");
        printf ("Location of current is %p \n", current);
        printf ("Value of X in last node: %d\n", current->x);

        printf ("Enter zero to terminate the loop: ");

        scanf ("%d",&d);

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

Comments

0

Aside from what simonc says (which is correct), you should probably set next to something in your loop as well.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.