1

我想将GSList放在GHashTable中,这是我管理所有这些的方式:

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

编译程序

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

所以这个程序产生了一个段错误,我不知道这是怎么发生的,因为我正确地将所有数据添加到列表中,并将列表添加到哈希表中,关于如何解决这个问题的任何想法?

4

1 回答 1

2

代码的下一部分是错误的,只需将其删除即可

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

使用这个添加功能:

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);
}
于 2010-09-04T14:31:51.503 回答