关于C#:Glib segfault g_free哈希表

Glib segfault g_free hash table

我不确定为什么要尝试释放段错误数据。任何帮助将不胜感激。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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);
}

在此示例中,您已经展示了无休止的segfault战斗,您没有为变量q分配或新建内存...由于某些原因,您已跳过了显示在您的main函数中....线索在指向char即q的指针上,是否具有malloc d内存...

您是否尝试过这种方式:

1
2
3
4
5
6
7
8
9
10
11
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尝试取消引用未分别为malloc d和new d的内存时发生段错误....如果您free d或delete da指针,它不是free d或new d ....