在 C 中初始化结构体 GHashTable

Initialize the struct GHashTable in C

我的问题与 GLib、C 编程有关。 当我初始化结构 GHashtable 时。

struct _GHashTable
{
gint             size;
gint             mod;
guint            mask;
gint             nnodes;
gint             noccupied;  /* nnodes + tombstones */

gpointer        *keys;
guint           *hashes;
gpointer        *values;

GHashFunc        hash_func;
GEqualFunc       key_equal_func;
gint             ref_count;
GDestroyNotify   key_destroy_func;
GDestroyNotify   value_destroy_func;

};

GHashTable *hash_table;
hash_table = (GHashTable *)malloc(sizeof(GHashTable));

在我的 hash_table 中,我有三个数组来存储键、值和哈希值。

gpointer        *keys;
guint           *hashes;
gpointer        *values;

我在初始化函数中初始化了那些数组:

hash_table->keys = malloc(sizeof(gpointer) * hash_table->size);
hash_table->values             = hash_table->keys;
hash_table->hashes = malloc(sizeof(guint) * hash_table->size);

我的问题是当我在分配内存后显示 hash_table 时,我发现值数组中存储了一个数字。

[0] key: (null) hash: 0 values: (null)
[1] key: (null) hash: 0 values: (null)
// Where is the 64273 comes from? Why other array are 
// initialized as 0 or null. Only this index is initialized like that?
[2] key: (null) hash: 64273 values: (null)
[3] key: (null) hash: 0 values: (null)
[4] key: (null) hash: 0 values: (null)
[5] key: (null) hash: 0 values: (null)
[6] key: (null) hash: 0 values: (null)
[7] key: (null) hash: 0 values: (null)

我是否必须手动初始化键、值和哈希数组,在为它们分配内存后将值分配为 0 或 NULL?

不赋0或NULL,一些随机数或垃圾数会这样出来?

谢谢。

来自 malloc() 的手册页:

malloc() allocates size bytes and returns a pointer to the allocated memory. The memory is not cleared.

因此为您的结构和数组分配的内存未初始化。它们可以是零或任何其他值。

如果要将分配的内存清零,需要使用 memset 来执行此操作:

hash_table = malloc(sizeof(GHashTable));
memset(hash_table, 0, sizeof(*hash_table));

对于你的数组,你可以使用 calloc 这样做,这也有将分配的内存清零的副作用:

hash_table->keys = calloc(hash_table->size, sizeof(gpointer));
hash_table->values = hash_table->keys;
hash_table->hashes = calloc(hash_table->size, sizeof(guint));

另请注意,malloc 系列函数的 return 值不应在 C 中进行类型转换。这样做会隐藏代码中的错误,例如 #include <stdlib.h> 查看 this question 了解更多详情。

您不应该自己初始化 GHashTableGHashTable 结构在 public headers 中不完整并且是私有的 API。它可以更改,恕不另行通知。您应该调用 g_hash_table_new (or g_hash_table_new_full),这将分配内存并正确初始化散列 table.