I'm trying to free a double linked list and my question is if I also need to free all the data and pointers in every node. Thank you.
Function:
static void free_list(Room *head, Room *head2) {
Room *tmp = head;
Room *tmp2 = head2;
Room *store;
Room *store2;
tmp = head2;
tmp2 = head;
printf("\nFreeing trap list...\n");
sleep(2);
while (tmp != NULL) {
store = tmp->pNext;
free(tmp);
tmp = store;
}
printf("\nFreeing rooms list...\n");
sleep(2);
while (tmp2 != NULL) {
store2 = tmp2->pNext;
free(tmp2);
tmp2 = store2;
}
}
Structure:
typedef struct Room {
struct Room *forward;
struct Room *left;
struct Room *right;
struct Room *previous;
struct Room *pPrev;
struct Room *pNext;
Room_Type Room_Type;
bool emergency_call;
} Room;
So do I also need to free, in the example, the forward pointer and also the other types as well? head
and head2
are two different pointers, each points to the start of two different lists.
This way of defining the container is very confusing:
typedef struct Room{
struct Room* forward;
struct Room* left;
struct Room* right;
struct Room* previous;
struct Room* pPrev;
struct Room* pNext;
Room_Type Room_Type;
bool emergency_call;
} Room;
Divide and conquer:
typedef struct Node {
struct Node* pPrev;
struct Node* pNext;
Room_Type Room_Type;
bool emergency_call;
} Node;
typedef struct List {
struct Node* pHead;
struct Node* pTail;
} List;
With this approach, one loop is enough:
void free_list(List *list)
{
Node *node = list->pHead;
while (node != NULL)
{
Node *next = node->pNext;
free(node);
node = next;
}
free(list);
}