Reputation: 15
I'm trying to create a traversable linked list, but my program crashes when I try to add an element to the list. I've tried many things but I can't figure out what I'm doing wrong.
typedef struct node_t node_t;
typedef struct list_t list_t;
struct node_t {
void *data;
node_t *prev;
node_t *next;
};
struct list_t {
node_t front;
node_t back;
};
list_t* listEmpty () {
list_t *list = malloc (sizeof (list_t));
list->front.prev = NULL;
list->front.next = &(list->back);
list->back.prev = &(list->front);
list->back.next = NULL;
return list;
}
void listPushFront (list_t *list, void *data) {
node_t *newNode = malloc (sizeof (node_t));
newNode->data = data;
newNode->prev = &(list->front);
newNode->next = list->front.next;
list->front.next->prev = newNode; //CRASHES HERE
list->front.next = newNode;
}
int main (int argc, char *argv[]) {
list_t *list = malloc (sizeof (list_t));
int a = 6;
void* pa = &a;
listEmpty(list);
listPushFront (list, pa);
return 0;
}
Upvotes: 0
Views: 86
Reputation: 18348
This is wrong in so many ways.
int main (int argc, char *argv[]) {
list_t *list = malloc (sizeof (list_t));
Why are you doing this in main
?
Why do you call listEmpty
with parameter list
?
listEmpty(list);
Your listEmpty
function doesn't do anything with the parameter you pass to it.
You're not doing anything with the pointer that your listEmpty
returns, so how do you expect it to propagate to the following call of listPushFront
?
Upvotes: 0
Reputation: 1016
listEmpty()
returns a list, and has a void argument. In main()
however you pass it a list, and don't capture its return value.
#include <stdlib.h>
typedef struct node_t node_t;
typedef struct list_t list_t;
struct node_t {
void *data;
node_t *prev;
node_t *next;
};
struct list_t {
node_t front;
node_t back;
};
list_t* listEmpty (void) {
list_t *list = (list_t *)malloc (sizeof (list_t));
list->front.prev = NULL;
list->front.next = &(list->back);
list->back.prev = &(list->front);
list->back.next = NULL;
return list;
}
void listPushFront (list_t *list, void *data) {
node_t *newNode = (node_t *)malloc (sizeof (node_t));
newNode->data = data;
newNode->prev = &(list->front);
newNode->next = list->front.next;
list->front.next->prev = newNode;
list->front.next = newNode;
}
int main (int argc, char *argv[]) {
list_t *list = 0;
int a = 6;
void* pa = &a;
list = listEmpty();
listPushFront (list, pa);
return 0;
}
Upvotes: 2
Reputation: 455000
Your list is not being initialized properly and this is leading to the crash.
listEmpty(list);
should be
list = listEmpty();
Upvotes: 0