I just wrote a simple linked list, however when iterating through the list via add() and display() the 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;
for (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;
for (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 the code on a few machines and it works on a few and doesn’t on others. I’m clueless about the source of the error.
In addition to the wrong size passed to
mallocthat FatalError mentioned, you allocate memory forl->itemsbut don’t ever set
l->items->valueto anything, so it’s an uninitialised pointer and when you try to dereference it when printingin the first iteration of the loop, that can easily lead to a segfault even if the insufficient allocation size didn’t cause one before.