Thread: Does it matter where free(node) is placed in this code? (Recursion)

  1. #1
    Registered User
    Join Date
    Feb 2014
    Posts
    7

    Does it matter where free(node) is placed in this code? (Recursion)

    I'm doing some C programming exercise questions and am not sure about this one:

    Does it matter if we place the "free(node);" statement before the recursive call? Please explain.

    Code:
    void deleteList(struct contact* node) {
    
      if (node != NULL) {        
      deleteList(node->next);    
    
      free(node);
      }
      }
    
    I was thinking it does matter because if free(node) were placed above the recursive call it would delete the node and then there would be no connection to the next element of the linked list. Is this correct thinking?

    Thanks.

  2. #2
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,791
    That would be correct.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Location
    Australia
    Posts
    375
    You could create a local variable to point at node->next though and then there would be no problem in deleting node before the recursive call. This creates a local variable though which is kind of a drawback with a recursive implementation.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. want to return a node using recursion
    By Xu Zhang in forum C++ Programming
    Replies: 6
    Last Post: 03-27-2013, 09:14 PM
  2. linked list node removal using 'free'
    By Rondane in forum C Programming
    Replies: 3
    Last Post: 11-20-2011, 03:25 PM
  3. Code for deleting a tree node not working
    By Mini in forum C Programming
    Replies: 2
    Last Post: 10-09-2010, 05:16 AM
  4. Replies: 0
    Last Post: 09-16-2008, 05:04 AM
  5. Make node code - right?
    By MethodMan in forum C Programming
    Replies: 1
    Last Post: 03-24-2002, 02:31 PM