开发者

GLib Hash Table - Pointer

开发者 https://www.devze.com 2022-12-22 00:52 出处:网络
I\'m trying to increment the value of some specific key if it was found. For some reason I keep getting the (pointer) address when I dump all keys:values from the hash table.

I'm trying to increment the value of some specific key if it was found. For some reason I keep getting the (pointer) address when I dump all keys:values from the hash table.

Output
      a: 153654132 // should be 5
      b: 1 
      c: 153654276 // should be 3
      d: 1 
      e: 1 
      f: 153654420 // should be 3


int proc()
{
    struct st stu;
    gpointer ok, ov;

    //... some non-related code here

    if(!g_hash_table_lookup_extended(table, key, &ok, &ov)){
        stu.my_int = g_malloc(sizeof(guint));
        *(stu.my_int) = 0;
        g_hash_table_insert(table, g_strdup(key), GINT_TO_POINTER(1));
    }else{
        stu.my_int = g_malloc(sizeof(guint));
        *(stu.my_int)++;
        g_hash_table_insert(table, g_strdup(key), stu.my_int);
    }   
}

Any 开发者_如何学Cideas will be appreciate it.


++ is higher precedence than *. So you are incrementing the pointer stu.my_int itself, rather than what it points to. You probably want (*stu.my_int)++.


I counted 7 errors in 8 lines:

/* 1) ov, the actual value read from the hash table, is never used */
if(!g_hash_table_lookup_extended(table, key, &ok, &ov)){
    stu.my_int = g_malloc(sizeof(guint));
    *(stu.my_int) = 0;
    /* 2) stu.my_int not freed: memory leak */
    g_hash_table_insert(table, g_strdup(key), GINT_TO_POINTER(1));
    /* 3) g_strdup(key) not freed: memory leak */
}else{
    stu.my_int = g_malloc(sizeof(guint));
    /* 4) stu.my_int not freed: memory leak */
    /* 5) stu.my_int not initialized: stu.my_int contains junk */
    *(stu.my_int)++;
    /* 6) incrementing a pointer, not the value pointed by */
    g_hash_table_insert(table, g_strdup(key), stu.my_int);
    /* 7) g_strdup(key) not freed: memory leak */
}

Here is how I'd write that (not tested):

gpointer ov;
gint value;

/* ... */

if(g_hash_table_lookup_extended(table, key, NULL, &ov)) {
    value = GPOINTER_TO_INT(ov);
} else {
    value = 1;
}

g_hash_table_insert(table, key, GINT_TO_POINTER(value));
0

精彩评论

暂无评论...
验证码 换一张
取 消