C Question

Associate
Joined
1 Mar 2010
Posts
1,389
Let's say I am implementing a Linked List and I have the following structures:

Code:
typedef struct Node
{
    void *element;
    struct Node *nextNode;
} Node;


typedef struct LinkedList
{
    Node *head;
} LinkedList;

I also have various functions including:

Code:
Node *createNode( void *element, Node *nextNode );
void destroyNode( Node *node );

LinkedList *LinkedList_init( void );

Now, in both createNode() and LinkedList_init() I use malloc() to allocate the memory needed by the structure therefore I need to free this memory when I no longer have any need for the structures.

The Question:

If I initialise a linked list ( LinkedList *list = LinkedList_init(); ) how would I free the memory? Would I need to invoke destroyNode( list->head ) or is it simply free( list ) ?
Code:
void destroyLinkedList( LinkedList *list )
{
    destroyNode( list->head );
    free( list );
}

or

void destroyLinkedList( LinkedList *list )
{
   free( list );
}

Thanks!
 
I would *guess* that freeing list will only delete the pointer, not the linked data.

Ah, I see what you mean. I am only de-allocating the head node therefore the remaining list nodes are just sitting there taking up memory and being useless.

Edit: Something like this?

Code:
void destroyLinkedList( LinkedList *list )
{
    Node *currentNode = list->head;
    Node *temp;

    while ( currentNode != NULL )
    {
        temp = currentNode->nextNode;
        destroyNode( currentNode );
        currentNode = temp;
    }

    free( list );
}
 
Last edited:
Back
Top Bottom