0

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?

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

You are not allocating memory:

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

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

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.