Search code examples
cpointersstructlinked-listsingly-linked-list

Issue with a first-class linked list implementation in C


I am a newbie at programming at C and I am learning from a book so I apologize if the following is too basic. I am trying to implement first-class linked lists and the following program when executed gives me the error "Segmentation fault: 11".

#include <stdlib.h>

typedef struct node* link;
typedef struct node {int item; link next;} node;
typedef struct linked_list {link head; link tail;} linked_list; 

int main(void)
{
    link x;
    x = malloc(sizeof(node));
    x->next = NULL;
    x->item = 12;

    linked_list* l;
    l->head = x;
}

The same program without the linked list pointer and instead just with:

linked_list l;
l.head = x;

runs just fine. However, I'll need multiple lists around so I will ultimately want the pointer and I can't seem to figure out what is going wrong. Does anyone know a possible solution? Thank you in advance.


Solution

  • I am trying to implement first-class linked lists

    The term "first class linked list" is senseless. Actually what you are trying to implement is a two-sided singly-linked list.

    In this code snippet

    linked_list* l;
    l->head = x;
    

    you are using an uninitialized pointer l that has an indeterminate value. So dereferencing it results in undefined behavior.

    Instead you could write for example

    linked_list l = { .head = x, .tail = x };
    

    declaring an object of the structure type and initializing its both data members.

    If you want to use pointers to linked lists then allocate objects of the type linked_list dynamically as for example

    linked_list* l = malloc( sizeof( *l ) );
    l->head = x;
    l->tail = x;
    

    Strictly speaking initially the lists should be empty.

    linked_list* l = malloc( sizeof( *l ) );
    l->head = NULL;
    l->tail = NULL;
    

    You need to write a function that will add new nodes to the linked lists.