// by Joe Gillotti - 10/16/2011 // Linked list example // Verified with Valgrind to not leak memory or have other issues #include #include // Our linked list node struct record { int value; // Store a number here struct record* next; // Pointer to next node in list }; // Add record. Pass me reference to list and number to add void addRecord(struct record** list, const int num) { // Register memory for this new node struct record* ltmp = (struct record*) malloc(sizeof(struct record)); if (ltmp == NULL) { fprintf(stderr, "Couldn't allocate memory\n"); exit(1); } // Make its next item the previous node ltmp->next = *list; // Set the value ltmp->value = num; // Now replace the list we passed with the new node which has the // previous node in memory *list = ltmp; } int main () { // Head element of the linked list here struct record* list = NULL; // Place holder for each node struct record* tmp; // Stuff it with some shit int i = 5; while(--i) { addRecord(&list, i); } // Go through it, printing the value of each for (tmp = list; tmp; tmp = tmp->next) { printf ("%d\n", tmp->value); } // Now properly go through and free the ram for each node that // we're done with it // Place holder for each current node to kill struct record* old; // Iterate over for (tmp = list; tmp;) { // Save current node here old = tmp; // Incerement iterator to the next node tmp = tmp->next; // Kill current node free(old); } return 0; }