devnp
devnp

Reputation: 101

Linked list program crashes while building a next node

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]# 

Upvotes: 0

Views: 91

Answers (2)

simonc
simonc

Reputation: 42165

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);

        }
}

Upvotes: 5

Mats Petersson
Mats Petersson

Reputation: 129314

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

Upvotes: 0

Related Questions