Search code examples
clistmemorystructfree

Freeing data in a linked list


Hey I am currently working on a tasks where I need to delete specific nodes in a list. I also need to free the memory of those nodes. This is the given struct:

typedef struct      s_list
{
    struct s_list   *next;
    void            *data;    
}                   t_list;

The function I need to create gets passed a function which free's the data of the node.

void remove_node(t_list **begin_list, void (*free_fct)(void *))
//free_fct being the function to free data.

So my question is: Why can't we just free the node, like this?:

s_list *node = *begin_list)
free(node)

Why does the task provide a function to specifically free data? My guess would be that if I only free the node the data would still be in stored Memory but wouldn't that mean next needs to be freed aswell?

Also I don't know what a free_fct function could look like. If data would be string, how would a free_fct function look like?


Solution

  • The point is to make the list more generic. If you just free the data pointer in your remove_node function, you basically can only store pointers to memory allocated by malloc, calloc and realloc in the data pointer. Furthermore, consider data field of a node points to an instance of following struct:

    struct some_struct{
        FILE *file;
        int *intArray;
    }
    

    That struct might have been dynamically allocated with malloc, so you can free it with free. But file may contain a valid filehandle, and intArray may be a pointer to a dynamically allocated int array. By just freeing data, you would create a ressource leak in this case. However, if your list implementation allows you to pass a "destructor" function, you can pass a function like:

    void SomeStructDestructor(void* data){
        struct some_struct *temp = (struct some_struct*)data;
        close(temp->file);
        free(temp->intArray);
        free(data);
    }