Reputation: 141
I'm fairly new to C pointers so I'm trying to play around with them to figure out how they work, more in depth.
I've got the following data types, defined with typedef
:
struct node
{
int key;
struct node * prev;
struct node * next;
};
typedef struct node node_t;
struct list
{
node_t * head;
node_t * tail;
};
typedef struct list list_t;
My goal is to have a doubly linked list with a pointer to its head and its tail, maybe with tail->next
pointing to the head; in order to have a circular list.
The problem is that whenever I try to refer to any of the node's pointers, I get a segmentation fault.
I coded a function like this:
list_t * create_new_list()
{
list_t * new_list;
new_list->head = malloc( sizeof(node_t) );
new_list->tail = malloc( sizeof(node_t) );
// I've also tried
// list * new_list = malloc( sizeof(list_t) );
// but it doesn't work */
/* init the head node */
new_list->head->prev = NULL;
new_list->head->next = NULL;
new_list->head->key = 0;
/* init the tail node */
new_list->tail->prev = NULL;
new_list->tail->next = NULL;
new_list->tail->key = 0;
return new_list;
}
When I call create_new_list()
from my main()
function I get:
"Segmentation Fault. Core dump created".
int main()
{
list_t * my_list = create_new_list();
return EXIT_SUCCESS;
}
Upvotes: 1
Views: 71
Reputation: 44339
Your problem is that you never allocate any memory for the new list. Consequently
´new_list->head = ... `
will crash.
Try:
list_t * create_new_list()
{
list_t * new_list = malloc(sizeof *new_list); // Allocate a new list
if (!new_list) exit(1); // Bail out if it failed
new_list->head = NULL; // Initialize pointers
new_list->tail = NULL; // Initialize pointers
return new_list; // Return the new list
}
Don't allocate any nodes in the create
function. Do that in an insert
function.
Something like:
void insert(list_t *list, int key)
{
node_t* new_node = malloc( sizeof *new_node );
if (!new_node) exit(1);
new_node->key = key;
//... add the code to insert the node into the list
}
Upvotes: 3
Reputation: 8142
list_t * new_list;
new_list->head = malloc( sizeof(node_t) );
This won't work as new_list
doesn't have a value! You need to allocate memory for it as well. Try doing this
list_t * new_list = malloc(sizeof(list_t));
Upvotes: 3