Search code examples
chashtableassociative-arrayglib

Get reference to key stored in GHashTable


I'm using a GHashTable from glib and I want to delete a key value pair by key. As described in the docs when calling g_hash_table_remove() you need to free the key and value yourself when they were dynamically allocated. But how do I get a pointer to the key so I can free it?

EDIT: I considered using g_hash_table_new_full but my use of GHashTable is so small that I considered this overkill. I would prefer freeing the key manually.

EDIT: As pointed out by Keine Lust g_hash_table_new_full shouldn't be less performant. You can also pass NULL for one of the destroy functions if you don't need it.


Solution

  • A simple way to free the associated data when an entry is deleted in the hash table is passing a free function to g_hash_table_new_full:

    GHashTable = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
    

    Parameters

    hash_func: a function to create a hash value from a key

    key_equal_func: a function to check two keys for equality

    key_destroy_func: a function to free the memory allocated for the key used when removing the entry from the GHashTable, or NULL if you don't want to supply such a function.

    value_destroy_func: a function to free the memory allocated for the value used when removing the entry from the GHashTable, or NULL if you don't want to supply such a function.