Thread: question about freeing resources

  1. #1
    Registered User
    Join Date
    Jan 2008

    question about freeing resources

    Given the follow struct for a doubly linked list:

    typedef struct Node {
        int value;
        struct Node *next;
        struct Node *previous;
    } nodeT;
    When I'm ready to release resources claimed by a nodeT object, do I also need to explicitly free next and previous, or is that automatically taken care of for me by freeing the encapsulating struct reference (i.e. free(node))? If so, is this because they are all occupying the shared space that is requested when memory is allocated using malloc?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    Wasn't this question asked just a few days ago?

    Edit: See this one:

    As a summary: If this is part of linked list, next/previous will point to other nodes, and you will need to free them separately, but when you destroy any particular node, it is either:
    * Deleting an individual node, in which case the next/previous nodes of the neighbouring nodes will have to be changed, but the current node's next/prev pointers shouldn't be freed.
    * Deleting the whole linked list - in this case, you have to walk the list, and delete each node until all of the list has been deleted. Care has to be taken that you don't delete the node first, then use the next or previous pointer to get to the next/previous node [most of the time this will appear to work fine, but given sufficient time/use, you will run into a situation where the freed memory is either unavailable after free, or has been overwritten by something else - it is undefined behaviour to access memory after it's freed, and thus "anything can happen"].

    Last edited by matsp; 03-07-2008 at 03:43 AM.
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 04-15-2009, 10:35 AM
  2. another do while question
    By kbpsu in forum C++ Programming
    Replies: 3
    Last Post: 03-23-2009, 12:14 PM
  3. Freeing Linked Lists
    By mrpickle in forum C Programming
    Replies: 4
    Last Post: 01-21-2004, 07:57 PM
  4. Question...
    By TechWins in forum A Brief History of
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Adding resources
    By nima_ranjbar in forum Windows Programming
    Replies: 0
    Last Post: 04-14-2002, 11:36 PM