tags:

views:

99

answers:

1

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

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 for add_inv within your main function.... the clue is on the pointer to char i.e. q, has that got mallocd memory...

Have you tried it this way:

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

A seg-fault occurs when you tried to de-reference memory that has not being mallocd nor newd depending on C/C++ respectively....it can happen if you freed or deleted a pointer that has not being freed or newd....

tommieb75
Thanks. I did as you indicated and seems to be working. Now I can remove that entry from the hash table g_hash_table_remove (hashtable, q); and g_free(old_key); but for some reason g_free(old_value); gives segfault.
Mike
@Mike: was old_value malloc'd or new'd?
tommieb75