Segfault bei verketteter Liste
-
Hallo,
ich wollte mich mal an einer verketteten Liste versuchen. Ich kriege aber immer einen Segfault:
Die Liste:
struct slist { struct node { char *content; struct node *next; } *head, *tail; };
Diese Funktionen erstellen bzw. löschen eine Liste:
int slist_new(struct slist* list) { list = (struct slist*) malloc(sizeof(struct slist)); if (list == NULL) { return EXIT_FAILURE; } list->head = NULL; list->tail = NULL; return EXIT_SUCCESS; } void slist_destroy(struct slist* list) { while (list->head != NULL) { struct node* tofree = list->head; list->head = list->head->next; free(tofree->content); free(tofree); } free(list); }
Und hier gibts den Segfault. Der Fehler tritt bei "if (list->head == NULL)" auf.
int slist_append(struct slist* list, char *data) { struct node* n = (struct node*) malloc(sizeof(struct node)); if (n == NULL) { return EXIT_FAILURE; } n->content = strdup(data); n->next = NULL; if (list->head == NULL) { list->head = n; list->tail = n; } else { n->next = NULL; list->tail->next = n; list->tail = n; } return EXIT_SUCCESS; }
Folgenden Code habe ich zum testen verwendet:
struct slist *users; if (slist_new(users) == EXIT_FAILURE) { printf(" [-] Could not allocate memory for user list\n"); exit(1); } char *t = "nick"; if (slist_append(users, t) == EXIT_FAILURE) { printf(" [-] Could not append user to list"); exit(1); } slist_destroy(users);
Ich weiß nicht woran es liegen könnte. Hat einer von euch vllt. einen Tipp?
Gruß pyro
-
int slist_new(struct slist* list)
*list is ne lokale variable. du willst struct slist **list haben.
-
Hm okay, daran lags wirklich.
Mir ist das Problem vorher noch nie aufgefallen. Wieso ist *list denn nur lokal?
-
weil du in der funktion nen pointer auf nen pointer brauchst um deinen users pointer aus main() ändern zu können.