Deallocate Linked List C

deallocate linked list C

Every time we add nodes we allocate memory dynamically. When we no longer need the list or the program exits we must free the allocated memory. Not doing this might result in memory leaks.

This short tutorial shows how to deallocate linked list. As in the other posts, this example is based on the linked list we created in our first example.

Deallocate linked list

This procedure goes as follows:

  1. We use temp to store the beginning of the list.
  2. We say that the list now starts with the second element.
  3. We free memory pointed by the temp variable.
  4. Repeat from step 1.
void deallocateList(struct Person* list) {
    struct Person* temp = list;
    while (list) {
        temp = list;
        list = list->next;
        free(temp);
    }
}

Main method:

int main() {
    struct Person* list = NULL;
    list = addNode(list, "mike", 23);
    list = addNode(list, "joe", 54);
    list = addNode(list, "sam", 30);
    list = addNode(list, "john", 28);

    printf("List size is: %d\n", list->listSize);
    printList(list);

    deallocateList(list);

    return 0;
}

This example has no output because the result can be seen only with a debugger.

FacebookTwitterLinkedin