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!
mallocjust allocates the memory, it does not initialize it in any way (for that you would wantcalloc). This means that e.g. the new nodesnextpointer will not beNULL, and that will matter with the function you shown in the question (I leave it as an exercise for the OP to figure out where).struct nodeas that affects the answer between "Alter Mann" and "jayeshbhoi" and howadd_entry()should be coded.