A
Andy Elvey
Hi all -
I've been poking around with C for a while, but I have big problems
with linked lists. This seems to be mainly around the "declaration,
initialisation, iterating" area. Anyway, I have the code below, which
compiles but gives a segfault (and I have no idea why), so hoping that
someone may be able to help.
( I have three puts statements at the end because I'm unsure how to
iterate along a list. )
Very many thanks if you can get this code working...... 
- Andy
I've been poking around with C for a while, but I have big problems
with linked lists. This seems to be mainly around the "declaration,
initialisation, iterating" area. Anyway, I have the code below, which
compiles but gives a segfault (and I have no idea why), so hoping that
someone may be able to help.
( I have three puts statements at the end because I'm unsure how to
iterate along a list. )
Code:
/* This code is released to the public domain */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
/* Linked list implementation */
typedef struct _List List;
struct _List {
void *data;
List *next;
};
static List *list_malloc (void)
{
return (List *) malloc (sizeof (List));
}
List *list_prepend (List *list, void *data)
{
List *ret = list_malloc ();
ret->data = data;
ret->next = list;
return ret;
}
List *list_append (List *list, void *data)
{
List *ret;
if (list == NULL) return list_prepend (list, data);
ret = list;
for (; list->next; list = list->next);
list->next = list_malloc ();
list->next->data = data;
list->next->next = NULL;
return ret;
}
void list_free (List *list)
{
List *next;
while (list)
{
next = list->next;
free (list);
list = next;
}
}
/* End linked list implementation */
int main()
{
/* Declare a list */
List *mylist = NULL;
list_append(mylist, "foo");
puts(mylist->data);
list_append(mylist, (int*) 42);
puts(mylist->data);
list_append(mylist, "baz");
puts(mylist->data);
return 0;
}
- Andy