tags:

views:

17

answers:

1

I would like to put a GSList inside a GHashTable, here is how I managed all of this:

#include <glib.h>
#include <glib/gprintf.h>

typedef struct Foo_ {
  GHashTable * bar;
} Foo;

Foo * create() {
  Foo * foo = g_malloc(sizeof(Foo));
  foo->bar = g_hash_table_new(NULL, NULL);
  return foo;
}

void add_element(Foo * foo, gchar * key, gpointer data) {  
  GSList * list = g_hash_table_lookup(foo->bar, key);

  if(list == NULL) {
    // init empty list
    list = g_malloc(sizeof(GSList));
    list->data = NULL;
    list->next = NULL;
  }

  list = g_slist_append(list, data);
  g_hash_table_insert(foo->bar, key, list);
}


void output_content(Foo * foo, gchar * key) {
  GSList * list = g_hash_table_lookup(foo->bar, key);
  guint length = g_slist_length(list); // 
  int idx;

  for(idx = 0; idx < length; idx++) {
    int * data = g_slist_nth_data(list, idx);
    g_printf("%d\n", *data); // segfault happens here, cause data == NULL
  }
}

int main() {
  Foo * foo = create();
  int data0 = 0;
  int data1 = 1;
  int data1bis = 11;
  int data1ter = 111;
  int data2 = 2;

  add_element(foo, "data0", &data0);
  add_element(foo, "data1", &data1);
  add_element(foo, "data1", &data1bis);
  add_element(foo, "data1", &data1ter);
  add_element(foo, "data2", &data2);

  output_content(foo, "data1");

  return 0;
}

compile the program with

gcc  -g -Wall -L  -I -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include  -lglib-2.0 -o main main.c

So this program generates an segfault, I don't know how this could happen, as I corretly added all the data to the list, and the list to the hash table, Any ideas on how I could solve this ?

A: 

the next portion of code is wrong just delete it

  if(list == NULL) {
    // init empty list
    list = g_malloc(sizeof(GSList));
    list->data = NULL;
    list->next = NULL;
  }`

go with this add function :

void add_element(Foo * foo, gchar * key, gpointer data) {  
  GSList * list = g_hash_table_lookup(foo->bar, key);

  list = g_slist_append(list, data);
  g_hash_table_insert(foo->bar, key, list);
}
phmr