Oliver
Oliver

Reputation: 3682

glib2 hash table: GINT_TO_POINTER macro

I don't think I understand the glib2's hash table, in particular, how to properly use GINT_TO_POINTER when both key and value are integers. I would think this is a use case for using g_int_hash and g_int_equal when you create a new hash table. However,the following snippet will seg faults.

#include <glib.h>

int main(void) {
    GHashTable * freq = g_hash_table_new(g_int_hash, g_int_equal);
    for (int i = 0; i < 10; i++) {
        g_hash_table_insert(freq, GINT_TO_POINTER(i), GINT_TO_POINTER(0));
    }
    g_hash_table_destroy(freq);
}

I know two ways to make it right: one is to create a hash table like this without changing anything else:

   GHashTable * freq = g_hash_table_new(g_direct_hash, g_direct_equal);

A second way is, keep creation as it is, but explicitly allocate space for both key and value:

   int * key = malloc(sizeof(int));
   int * value = malloc(sizeof(int));

then insert the key and value by casting it to (gpointer).

The second approach seems like a really tedious way of doing a key value pair, is this the proper way of doing int to int mapping? Thanks.

Upvotes: 2

Views: 1704

Answers (1)

ptomato
ptomato

Reputation: 57880

The documentation for g_int_hash() says:

Note that this function acts on pointers to gint, not on gint directly: if your hash table's keys are of the form GINT_TO_POINTER (n), use g_direct_hash() instead.

So yes, if you are doing int-to-int mapping, you should use g_direct_hash(), g_direct_equal(), and GINT_TO_POINTER().

Upvotes: 3

Related Questions