c - Iteration through linked list leads to Segmentation fault -
i wrote simple linked list, when iterating through list via add() , display() program seg faults.
#include <stdlib.h> #include <stdio.h> typedef struct entry { void *value; struct entry *next; } entry; typedef struct list { entry *items; } list; list *create(void) { list *l; l = malloc (sizeof(list)); l->items = malloc(sizeof(entry*)); l->items->next = null; return l; } void add(list *l, void *value) { entry *temp, *last, *new; (temp = l->items; temp != null; temp = temp->next) { last = temp; } new = malloc(sizeof(*new)); new->value = value; new->next = null; last->next = new; } void display(list *l) { entry *temp; (temp = l->items; temp != null; temp = temp->next) { printf("%s\n", temp->value); } } int main(void) { list *l = create(); add(l, "item1"); add(l, "item2"); add(l, "item3"); add(l, "item4"); display(l); return 0; } i have tested code on few machines , works on few , doesn't on others. i'm clueless source of error.
in addition wrong size passed malloc fatalerror mentioned, allocate memory l->items
list *create(void) { list *l; l = malloc (sizeof(list)); l->items = malloc(sizeof(entry*)); l->items->next = null; return l; } but don't ever set l->items->value anything, it's uninitialised pointer , when try dereference when printing
void display(list *l) { entry *temp; (temp = l->items; temp != null; temp = temp->next) { printf("%s\n", temp->value); } } in first iteration of loop, can lead segfault if insufficient allocation size didn't cause 1 before.
Comments
Post a Comment