Glib segfault g_free 哈希表
我不太清楚为什么如果我尝试释放数据会出现段错误。任何帮助将不胜感激。
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);
}
I'm not quite sure why if I try to free the data I get segfault. Any help will be appreciate it.
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这个示例中,您已经展示了无休止的段错误之战,您没有为变量
q
分配或新建内存...由于某种原因,您跳过了显示代码main
函数中的add_inv
...线索就在指向 char 的指针上,即q
,它有mallocd 内存...
您是否尝试过这种方式:
当您尝试取消引用尚未被
malloc
d 或new
d 的内存时,会发生段错误分别取决于 C/C++...如果您释放
或删除
尚未释放
的指针或<代码>新d....In this example that you have shown and the endless battle for segfault, you have not malloc'd or new'd the memory for the variable
q
...for some reason you have skipped showing the code foradd_inv
within yourmain
function.... the clue is on the pointer to char i.e.q
, has that gotmalloc
d memory...Have you tried it this way:
A seg-fault occurs when you tried to de-reference memory that has not being
malloc
d nornew
d depending on C/C++ respectively....it can happen if youfree
d ordelete
d a pointer that has not beingfree
d ornew
d....