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!

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Bec
  • 133
  • 4
  • 5
  • 13
  • 5
    "C: Correctly using malloc" - first of all, [don't cast its return value](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858). –  Jan 30 '14 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. – Fred Foo Jan 30 '14 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`](http://en.cppreference.com/w/c/memory/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). – Some programmer dude Jan 30 '14 at 13:54
  • Suggest posting `struct node` as that affects the answer between "Alter Mann" and "jayeshbhoi" and how `add_entry()` should be coded. – chux - Reinstate Monica Jan 30 '14 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. – Richard Schwartz Jan 30 '14 at 22:41

2 Answers2

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);
    }
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
2

way to free your list:

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

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

}
Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73