g_hash_table_new() 和 g_queue_new()

g_hash_table_new() and g_queue_new()

我有一个像这样的函数来初始化全局哈希图。

GHashTable* globalHT;

init() {
 GQueue* queue = g_queue_new();
 g_hash_table_insert (globalHT,
                     "key",
                     queue);

}

void main() {
   init();
   GQueue* myqueueRef = (GQueue*) g_hash_table_lookup (globalHT, "key");
   // Is myqueueRef valid here?
}

现在当我在 main() 中调用 init() 然后引用键值时,myqueueRef 是 NULL 还是有效?

我正在尝试确保 init() 中的自动变量 "queue" 不是本地变量,并且在 init() return

后不会停止存在

Now when I call init() inside main() and then reference the key-value, will myqueueRef be NULL or valid?

你的程序会崩溃,因为你没有使用 g_hash_table_new_full().

构造 globalHT

I am trying to make sure that the the auto variable "queue" inside init() is not local and does not cease to exist upon return of init()

这不是 heap-based C 中内存分配的工作方式。除非您使用 compiler-specific 功能,如 g_autoptr() 使用的功能(您应该这样做:它真的很有用),否则在一个范围内的堆上进行的分配仍将存在于另一个范围内的堆上,直到它被显式指定释放了。

阅读 C 中堆栈和堆分配之间的差异。