Re: glib question - what to free from hashes



Vlad GALU wrote:

Is it OK if I free the elem/key pairs from a hash table inside
the GHRfunc that I pass to g_hash_table_foreach_remove() ?

If you intend to free the hash table entry with a call to
g_hash_table_remove () inside the GHRFunc: NO!

The GHRFunc is merely meant to be a test function for the elements of
your hash table. It has just to DECIDE whether particular elements
should be freed or not. Actual freeing of entries is performed by
g_hash_table_foreach_remove () itself, if your GHRFunc indicates that
this is okay for the particular entry.

However,
if you intend to free the DATA pointed to by "key" and "value" with
g_free (), g_object_unref () or similar: YES!

Typical key/value pairs in a hash table consist of three items, each
consuming its own chunk of memory:
1. the data pointed to by the "key" pointer
2. the data pointed to by the "value" pointer
3. the hash entry containing the "key" and "value" pointers

Only 3. is freed by g_hash_table_foreach_remove () if GHRFunc permits
it and no further precautions have been taken.

If you were dynamically allocating the key and value data you were
passing to g_hash_table_insert () it is okay to free it inside the
GHRFunc. Although doing this is slightly less elegant than using
GDestroyNotify functions for that, it will certainly save one or two
function calls at runtime and thus be (very) slightly faster. However,
you should not free key/value data inside your GHRFunc if it returns
FALSE to g_hash_table_foreach_remove ()!

And you may only free data you were dynamically allocating on your own
before. If you fill a hash table with static data like constants then
you must not free that! GHashTable does NOT create own, dynamic copies
of the "key" and "value" data. Just POINTERS to them are copied and
stored in the hash entry.



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]