【问题标题】:Glib segfault g_free hash tableGlib segfault g_free 哈希表
【发布时间】:2010-03-11 19:04:10
【问题描述】:

我不太清楚为什么如果我尝试释放数据会出现段错误。任何帮助将不胜感激。

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

【问题讨论】:

    标签: c glib


    【解决方案1】:

    在这个例子中,你已经展示了无休止的段错误之战,你没有 malloc'd 或 new'd 变量 q 的内存...由于某种原因,你跳过了显示 @987654322 的代码@ 在你的 main 函数中......

    你有没有这样尝试过:

    int main(int argc, char *argv[]){ const char *qInit = "foo"; 字符 *q; 哈希表 = g_hash_table_new(g_str_hash, g_str_equal); ... q = strdup(qInit); /* 现在 q 已经分配了内存! */ add_inv(q); /* 这应该可以工作 */ g_hash_table_destroy(哈希表); }

    当您尝试取消引用既不是mallocd 也不是newd 的内存时会发生段错误,具体取决于C/C++ ....如果您使用freed 或@ 987654329@da 指针不是freed 或newd....

    【讨论】:

    • 谢谢。我按照你的指示做了,似乎正在工作。现在我可以从哈希表中删除该条目 g_hash_table_remove (hashtable, q);和 g_free(old_key);但出于某种原因 g_free(old_value);给出段错误。
    • @Mike: old_value malloc'd 还是 new'd?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多