I’m using a malloc’d string as a key to a GLib hash table. I then have several updates to make. Each update uses a newly malloced string that is identical in the actual sequence of characters. If I do an an insert, will the old string be overwritten? How can I make sure to free it so I don’t keep extra copies around? If it’s not overwritten, how can I make sure to implement an update without it being too slow?
Share
If you supply the correct comparator and key/value destructors to
g_hash_table_new_fullwhen creating the hash table, you don’t have to do anything extra. The table will understand that the key strings are the same even if they are separate copies, and it will automatically free repeated copies of the same key as well.Here is an example (the ugly
printfs are only there to show whats happening):First you write a destructor:
Then you instantiate and play around with the
GHashTable:Here is what a test run looks like:
You will see that if you create a ‘new’ key identical to an existing key, and try to insert a corresponding ‘new’ value, then the ‘insert’ operation automatically destroys the ‘new’ key (because it is the same as the existing one), as well as the old value (because it has to be replaced with the new one).