I have a function like this which initializes a global hashmap.
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?
}
Now when I call init() inside main() and then reference the key-value, will myqueueRef be NULL or valid?
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()
Now when I call init() inside main() and then reference the key-value, will myqueueRef be NULL or valid?
Your program will crash because you haven’t constructed globalHT
using g_hash_table_new_full()
.
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()
That’s not how heap-based memory allocation in C works. Unless you use compiler-specific features like those used by g_autoptr()
(which you should: it’s really useful), an allocation made on the heap in one scope will still be present on the heap in another scope until it’s explicitly freed.
Read up on the differences between stack and heap allocation in C.