2

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!

5
  • 5
    "C: Correctly using malloc" - first of all, don't cast its return value. Commented Jan 30, 2014 at 13:50
  • You should free nodes when you're done with them; out of context, it's hard to say when that should happen. Commented Jan 30, 2014 at 13:52
  • 1
    Remember that malloc just allocates the memory, it does not initialize it in any way (for that you would want calloc). This means that e.g. the new nodes next pointer will not be NULL, 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). Commented Jan 30, 2014 at 13:54
  • Suggest posting struct node as that affects the answer between "Alter Mann" and "jayeshbhoi" and how add_entry() should be coded. Commented Jan 30, 2014 at 17:32
  • You need to show us the call to free(). What I expect we should see is a loop that walks the list, starting at head and calling free somewhere along the line -- but order is important! If you get it wrong, you're likely to crash. So show us that part of the code so we can tell you. Commented Jan 30, 2014 at 22:41

2 Answers 2

4
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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

way to free your list:

void freeList(struct node* head)
{
   struct node* tmp;

   while (head != NULL)
    {
       tmp = head;
       head = head->next;
       free(tmp);
    }

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.