【发布时间】:2014-03-20 05:15:23
【问题描述】:
我会尝试在 Glib 哈希中存储许多列表(数组)。这是示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#define NR 10
typedef unsigned char carr[NR];
GHashTable* hasht;
int init = 0;
int main() {
carr *c, *d;
int i;
hasht = g_hash_table_new(g_str_hash, g_str_equal);
c = g_malloc0(sizeof *c);
for(i=0; i<NR; i++) {
*c[i] = 70+i;
}
for(i=0; i<NR; i++) {
printf("%d\n", *c[i]);
}
g_hash_table_insert(hasht, "1", c);
printf("----------------\n");
d = g_hash_table_lookup(hasht, "1");
for(i=0; i<NR; i++) {
printf("%d\n", *d[i]);
}
return 0;
}
你可以用这种方式编译这段代码:
gcc -Wall -o arrtest arrtest.c `pkg-config --cflags --libs glib-2.0`
如果我运行编译后的代码,我会得到这个错误:
*** Error in `./arrtest': malloc(): memory corruption: 0x00000000018efe70 ***
但是如果我改变上面两行的顺序:
hasht = g_hash_table_new(g_str_hash, g_str_equal);
c = g_malloc0(sizeof *c);
到这里:
c = g_malloc0(sizeof *c);
hasht = g_hash_table_new(g_str_hash, g_str_equal);
代码运行没有任何问题。
为什么?
该项目将存储许多列表,如下所示:
a = {0, 1, 3, 4, 2, 0, 5, 9, 20};
每个列表都有一个字符串键。函数应该是这样的:
store_in_hash(char * key, int idx)
从其他地方打来的。该函数检查全局哈希表是否存在,如果不存在,则创建它。然后查找键,如果不存在,则创建一个新键,并增加列表的第 idx 项。将许多列表存储在哈希表中的预期方式是什么?
感谢您的帮助:
空气
【问题讨论】:
-
你试过使用 valgrind 吗?
-
我从未使用过 valgrind :)。首先,没有它我会解决这个问题,但我会看到的 - 谢谢。
-
顺便说一句,
*c[i] = 70+i;(和类似的代码)没有按照您的想法做。 -
好吧,如果我将 'unsigned char' 更改为简单的 'int',那么它可以工作......为什么? :)
-
好的,那有什么问题?在这种情况下,*c[i] 是一个无符号字符,是不是 [0..255]?
标签: c glib memory-corruption