GLib Hash Table

Creating a HashTable:

priv->attributes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);

Add Data:

gboolean
gxml_tag_add_attribute (GxmlTag     *self,
                        const gchar *name,
                        const gchar *value)
{
  g_return_val_if_fail (GXML_IS_TAG (self), FALSE);

  GxmlTagPrivate *priv = gxml_tag_get_instance_private (self);

  return g_hash_table_insert (priv->attributes, g_strdup (name), g_strdup (value));
}

name and value are const gchar. This is correct, or should be:

gchar *nam = g_strdup(name);
gchar *val = g_strdup(value);

g_hash_table_insert(priv->attributes, nam, val);

g_free (nam);
g_free (val);

In function dispose:

g_hash_table_destroy (priv->attributes);

or the correct way is:

g_clear_pointer (&priv->attributes, g_hash_table_destroy);

g_free (nam);
g_free (val);

No, the hash table will not copy the key and the value for you; since it is generic, it cannot know what type exactly you passed and that’s why can pass custom free functions (g_free in your case) in the constructor.

What you are doing is basically creating a double free on g_hash_table_destroy (if that’s the question)

Whether or not to use g_hash_table_destory on its own or g_clear_pointer is mainly depending on whether you will encounter the hash table again after the destroy and rely on it being NULL

2 Likes

Thank you for your explanation.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.