Question

Below is the C program I have written. It contains an implementation of the doubly linked list.

#include <stdio.h>

/* node of a doubly linked list */
typedef struct _dlnode {
    struct _dlnode* prev;
    int key;
    struct _dlnode* next;
} dlnode;

/* doubly linked list */
typedef struct _dllist {
    dlnode* head;
    dlnode* tail;
} dllist;

/* returns an empty doubly linked list */
dllist* empty_dllist () {
    dllist* l;
    l->head=NULL;
    l->tail=NULL;
    return l;
}

int main()
{
    dllist* l;
    l=empty_dllist ();
    return 0;
}

I get the following runtime error:

Segmentation fault: 11

What is it caused by?

Was it helpful?

Solution

You have to allocate memory for a structure before you use a pointer to it to access its members. Change your function empty_dllist to -

dllist *empty_dllist(void) {
    dllist *l = malloc(sizeof *l);
    if(l == NULL) {
        // failed to allocate memory
        // handle it
        // return NULL
    }
    l->head = NULL;
    l->tail = NULL;
    return l;
}

OTHER TIPS

A segmentation fault is usually caused by trying to follow an uninitialized or NULL pointer.

In your program, you have pointer variable l in the function empty_dllist, and you try to follow that pointer to what it points to. But the variable is uninitialized, and cointains garbage, so it is not surprising that you get a segmentation fault.

You probably want to add a call to malloc in empty_dllist, to allocate a header struct for your list.

You are not allocating memory:

dllist* l = malloc(sizeof(dllist));

so trying to access l->head causes error memory access

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top