Behaviour of an hashtable using glib

 ̄綄美尐妖づ 提交于 2019-12-14 03:24:53

问题


I want to update the Volume to each @IP. So that for example after each 5 s I add V(i) of each @IP(i). Ok Now the hash table works fine it keeps updated after every T seconds. But the problem is that after a certain period I find that sometimes the same ip adress is repeated twice or even a lot of times within the hash table. So that when I close the process I find the same @IP repeated too many times. It is like there is a problem with the hash table or something like that.

Here is the code this funcion "update_hashTable()" is so important it is called every X seconds I suspect in fact a memory leak ... because I always call malloc for IP@. but it keeps working ... any idea ???

int update_hashTable( ... ) {

u_int32_t *a;

... //declarations

struct pf_addr *as;


as = ks->addr[0];

a = (u_int32_t*)malloc(sizeof(u_int32_t));

*a = ntohl(as->addr32[0]);

sz = value; // no matter it is... an int for example

if (ReturnValue=(u_int32_t)g_hash_table_lookup(hashtable, a)) {

  ReturnValue +=sz;
  g_hash_table_insert(hashtable, (gpointer)a, gpointer)ReturnValue);
}
else {
  g_hash_table_insert(hashtable, (gpointer)a, (gpointer)sz);
}

回答1:


Indeed, you appear to have a memory leak, but this isn't your problem. The problem is that the true-path of your if statement simply reinserts a second value associated with the same key, which is not what you want.

The typical pattern for this check-if-exists and increment algorithm is usually something like

gpointer val = g_hash_table_lookup(hash_table, key);
if (val == NULL) {
    val = g_malloc0(...);
    g_hash_table_insert(hash_table, key, val);
}
*val = /* something */;

The important thing to take away from this is that once you have a pointer to the value associated with some key, you can simply modify it directly.

If this code will be executed by multiple threads in parallel, then the entire block should be protected by a mutex, perhaps with GMutex: http://developer.gnome.org/glib/2.28/glib-Threads.html

gcc provides atomic builtin intrinsics, say for atomically incrementing the value, see http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html



来源:https://stackoverflow.com/questions/6178857/behaviour-of-an-hashtable-using-glib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!