首页 文章

Glib segfault g_free哈希表

提问于
浏览
0

我不太清楚为什么如果我试图释放数据我会遇到段错误 . 任何帮助将是欣赏它 .

struct mystu {
  char *q;
};

static GHashTable *hashtable;

static void add_inv(char *q)
{
    gpointer old_key, old_value;

    if(!g_hash_table_lookup_extended(hashtable, q, &old_key, &old_value)){
        g_hash_table_insert(hashtable, g_strdup(q), GINT_TO_POINTER(10));
    }else{
        (old_value)++;
        g_hash_table_insert(hashtable, g_strdup(q), old_value);
        g_hash_table_remove (hashtable, q); // segfault
        g_free(old_key);   // segfault
        g_free(old_value); // segfault
    }   
}
...
int main(int argc, char *argv[]){
  hashtable = g_hash_table_new(g_str_hash, g_str_equal);
  ...
  struct mystu stu;
  add_inv(stu.q);
  g_hash_table_destroy(hashtable);
}

1 回答

  • 0

    在这个你已经展示的例子和段落失败的无休止的争夺中,你没有malloc 'd or new' d变量的内存 q ...由于某种原因你跳过了在 main 函数中显示 add_inv 的代码....线索是指向char的指针,即 q ,是否有 malloc d内存...

    你有没有尝试过这种方式:

    int main(int argc, char *argv[]){
      const char *qInit = "foo";
      char *q;
      hashtable = g_hash_table_new(g_str_hash, g_str_equal);
      ...
      q = strdup(qInit); /* Now q has memory allocated! */
    
      add_inv(q); /* This should work */
    
      g_hash_table_destroy(hashtable);
    }
    

    当您尝试取消引用分别不依赖于C / C的内存时,也会发生seg-fault ....如果您没有 free d或_104225 new d ....

相关问题