Hello all; I haven't programmed anything in ages, and could use some help trying to recall how to properly initialize, free, and then reuse the same variables from within a loop. I'm working with a single linked list defined as
Code:
typedef struct __LLIST {
char *data;
struct __LLIST *next;
} list;
my variables are declared as
Code:
list base = { 0, 0 }, *node = &base, *tmp = 0;
Here's what I've tried; it *appears* to work on the first run but throws an exception on the next iteration of the control loop.
Code:
control loop {
// prompt user for string
// read string into static char array
// split string using strtok: p = strtok(user_input, " ");
while(p) {
node->next = malloc(sizeof(*node));
node = node->next;
node->data = malloc(strlen(p) + 1);
strcpy(node->data, p);
node->next = 0;
p = strtok(0, " ");
}
// do stuff with list
// try to free and reuse it
node = &base;
tmp = 0;
while(node) {
tmp = node;
free(node->data);
node = node->next;
free(tmp);
}
node = 0;
tmp = 0;
memset(&base, 0, sizeof(list));
node = &base;
}
Any ideas/help would be greatly appreciated.