【问题标题】:GLib Hash Table - PointerGLib 哈希表 - 指针
【发布时间】:2010-03-08 02:49:16
【问题描述】:

如果找到某个特定键,我会尝试增加它的值。出于某种原因,当我从哈希表中转储所有 keys:values 时,我不断获取(指针)地址。

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);
    }   
}

任何想法将不胜感激。

【问题讨论】:

  • 修复:我将第二个插入替换为:(ov)++; g_hash_table_insert(table, g_strdup(key), ov);

标签: c gtk glib


【解决方案1】:

++ 的优先级高于 *。因此,您正在增加指针 stu.my_int 本身,而不是它指向的内容。你可能想要 (*stu.my_int)++。

【讨论】:

    【解决方案2】:

    我数了 8 行 7 个错误:

    /* 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 */
    }
    

    这是我的写法(未经测试):

    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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      相关资源
      最近更新 更多