Search code examples
cstructundefined-behaviorsingly-linked-listfunction-definition

linked list implemetation from scratch, segmentation fault


I want to implement linked list from scratch. I programmed it, but when I run it gives me a Segmentation fault in my node_adder(int data) function. I don't know what caused this.

struct linked_list
{
    int value;
    struct linked_list *next;
};

struct linked_list *head = NULL;
struct linked_list *tail = NULL;

void node_adder(int data)
{
    struct linked_list *new = NULL;

    new->value = data;
    new->next = NULL;

    if (head == NULL)
    {
        head = new;
        tail = new;
        printf("head added\n");
    }
    else
    {
        tail->next = new;
        tail = new;
        printf("tail added\n");
    }
}

Solution

  • In node_adder(), you are not allocating any memory for the new node before accessing its members.

    Try this instead:

    struct linked_list
    {
        int value;
        struct linked_list *next;
    };
        
    struct linked_list *head = NULL;
    struct linked_list *tail = NULL;
    
    void node_adder(int data)
    {
        struct linked_list *newNode;
    
        // ADD THIS!!!
        // in C:
        newNode = malloc(sizeof(struct linked_list));
        // in C++:
        newNode = new linked_list;
        //
    
        newNode->value = data;
        newNode->next = NULL;
    
        if (head == NULL)
        {
            head = tail = newNode;
            printf("head added\n");
        }
        else
        {
            tail->next = newNode;
            tail = newNode;
            printf("tail added\n");
        }
    }