August Flanagan
August Flanagan

Reputation: 896

Glib hash table storing incorrect keys

I'm using glib for the first time and am having some trouble with a hash table. I'm trying to use uint32_t as the keys.

GHashTable *fwd_table = g_hash_table_new(g_int64_hash, g_int64_equal);

// some code here

while(something is true) {
  uint32_t net_addr = ip_strtoint(addr) - net_mask(addr);  // value of the key

  printf("The net_addr  is %u\n",net_addr);
  g_hash_table_insert(fwd_table, g_memdup(&net_addr, sizeof(net_addr)), 
                      g_memdup(num_id, sizeof(num_id)));

}

void dump_pair (const uint32_t *key, const char *value) {
  g_print ("Key: %u Value: %s\n", key, value);
}

g_hash_table_foreach (fwd_table, (GHFunc)dump_pair, NULL);

The output is:

The net_addr  is 3232301056
The net_addr  is 3232251904
The net_addr  is 3232284672
The net_addr  is 3232251686
The net_addr  is 3372220416

Key: 6307440 Value: 1
Key: 6307536 Value: 2
Key: 6307728 Value: 5
Key: 6307344 Value: 3
Key: 6307632 Value: 7

The keys should correspond to the net_addr. Any ideas what I'm doing wrong here?

Upvotes: 0

Views: 554

Answers (3)

dtoux
dtoux

Reputation: 1884

You are using uint32_t as a key and yet you declared g_hash_table_new(g_int64_hash, g_int64_equal) with 64-bit keys. Why don't you re-declare it as g_hash_table_new(g_int32_hash, g_int32_equal).

If you still want to use it as is you would need to zero out all 64 bit of the key before copying a new value in it.

Upvotes: 0

alk
alk

Reputation: 70941

What about dereferencing the key pointer in dump_pair()?

g_print ("Key: %u Value: %s\n", *key, value);

Upvotes: 1

unwind
unwind

Reputation: 399863

Could it be that the num_id variable should have its address taken when you duplicate it in the insert call?

I.e.

g_memdup(num_id, sizeof(num_id))

should be

g_memdup(&num_id, sizeof(num_id))

It's a bit difficult to be sure since you don't show the type of num_id, but since that argument corresponds to the value stored in the table, it should be a pointer.

It would make more sense to collect your key and value into a single struct, and insert those.

Upvotes: 0

Related Questions