Reputation: 78
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?
Upvotes: 0
Views: 185
Reputation: 9680
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;
}
Upvotes: 1
Reputation: 3325
You are not allocating memory:
dllist* l = malloc(sizeof(dllist));
so trying to access l->head causes error memory access
Upvotes: 0
Reputation: 27632
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.
Upvotes: 0