I've just started out learning C, and (seemingly) so far most stuff is clicking. However, I'm having some trouble tracking down an issue with an attempt at a double linked list. I keep getting a seg-fault
when I attempt to build/run this code. I'm compiling with the Cygwin supplied gcc via NetBeans.
I hate to just dump a block of code and say "help", but I don't know what other details are pertinent at this time, so feel free to ask for details if necessary:
#include <stdio.h>
#include <stdlib.h>
struct node_t{
struct node_t *prev;
struct node_t *next;
};
struct list_t{
struct node_t *head;
struct node_t *tail;
int length;
};
struct node_t *new_node(void);
struct list_t *new_list(void);
int append_list_node(struct list_t *list, struct node_t *node);
int main(void) {
int i = 0, length = 0;
struct node_t *node;
struct list_t *list = new_list();
for(i = 0; i < 10; i++){
length = append_list_node(list, new_node());
printf("%d", length);
}
return 0;
}
struct node_t *new_node(void){
struct node_t *node = malloc(sizeof(struct node_t));
return node;
}
struct list_t *new_list(void){
struct list_t *list = malloc(sizeof(struct list_t));
list->length = 0;
return list;
}
int append_list_node(struct list_t *list, struct node_t *new_node){
if(list->head == NULL){
list->head = new_node; // edited
new_node->prev = NULL;
}else{
list->tail->next = new_node;
new_node->prev = list->tail;
}
return (++list->length);
}
Thanks for the super quick responses everyone, all the answers are correct. As I was briefly looking over the code between F5
-ing, I realized I wasn't setting the tail
, so I resolved to change the line marked edited
as follows:
list->head = list->tail = new_node;
I'll also resolve to use calloc()
however, I've read that frequent use of it can cause considerable costs to execution time since it's clearing and allocating. Thoughts?