C: Correctly using malloc for linked list
10,009
Solution 1
void free_list(struct node *head)
{
struct node *temp;
while (head) {
free(head->m_first_name);
free(head->m_last_name);
free(head->m_address);
free(head->m_telephone);
temp = head;
head = head->m_next;
free(temp);
}
}
Solution 2
way to free your list:
void freeList(struct node* head)
{
struct node* tmp;
while (head != NULL)
{
tmp = head;
head = head->next;
free(tmp);
}
}
Author by
Bec
Updated on June 04, 2022Comments
-
Bec almost 2 years
I am a beginner to C and have a question about the proper use of malloc/free for pointers, particularly in linked lists. I have implemented a method to add a new node to my linked list. The node "head" is a global variable. After creating a new node, I insert it at the front of my list and reassign head to point to it. Here is the code:
int add_entry(char* first_name, char* last_name, char* address, char* telephone) { struct node* new_node = (struct node*) malloc(sizeof(struct node)); strcpy(new_node->m_first_name, first_name); strcpy(new_node->m_last_name, last_name); strcpy(new_node->m_address, address); strcpy(new_node->m_telephone, telephone); if (num_nodes == 0) head = new_node; else { new_node->m_next = head; head = new_node; } num_nodes++; return 1; }
We were told in class that anytime we use malloc, we should also use free. However, in this case use of free for new_node at the end of the program leads to a segmentation fault. What is the proper way to free memory in this case? Thanks!