Search code examples
cdynamic-memory-allocationglib

How to correctly free a GHashTable of structs


I do not know how to free all memory used, especially for GHashTable. I have something like this:

struct person 
{ 
   char *name;
   int age; 
};

void free_person(gpointer p){
    struct *address person = p;
    if (NULL == person)
        return;
    if(NULL != person->name)
       g_free(person->name);
    g_free(person);
}

And in main:

GHashTable *persons_info list = g_hash_table_new_full(..., ... , NULL, free_person);
struct person * person1 = g_try_malloc0(sizeof(struct person));
person1->age = 20;
char *name = g_strdup("Raul");
person1->name = g->strdup(name);
g_hash_table_insert(list, 2, person1);
 //Now for free...

g_hash_table_destroy(list);
list = NULL;

//Or g_hash_table_unref(list); ?
 
//What about person1 and name? //Should be Fred or just set to Null?

//If I add the following 2 lines sometimes I got sgm fault
free_person(person1):
person1 = NULL;


Knows someone the cause of sgm fault if I free variable person 1?


Solution

  • If created with g_hash_table_new_full(), then g_hash_table_destroy() will call the provided key free function and value free function on all the keys and values in the hash table. So you don't have to free them yourself. If you do, then you will be freeing them twice, which is why you get the segfault.

    If you used g_hash_table_new(), or you gave NULL as the key free function and/or value free function, then you do have to free them yourself.