c - 递归中的 g_hash_table_lookup

标签 c linux

我编写了以下玩具程序来在递归中测试“g_hash_table_lookup()”:


#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <glib.h>
#include <string.h>

void f_recursive(GHashTable *htable, int level){
    char key[] = "test_key";
    char value[] = "test_value";
    char *returned_value;

    if(level > 0){
        f_recursive(htable, level - 1);
    }
    else if(level==0){
        g_hash_table_insert(htable,&key[0],&value[0]);
    }

    returned_value = g_hash_table_lookup(htable,&key[0]);
    printf("Level=%d, Returned Value=%s\n",level, returned_value);
}

int main(int argc, char * argv[]){
    int i=3;
    GHashTable *Hash_Table;

    Hash_Table = g_hash_table_new(g_str_hash,g_str_equal);
    f_recursive(Hash_Table, i);
}

这段代码的目标只是调用一个递归函数,该函数在递归的每一层都在哈希表中查找仅在递归的最低层插入的键的值。我的期望是在递归的每一层我都可以恢复在最低层插入的值,因此该程序的预期输出应该是:

Level=0, Returned Value=test_value
Level=1, Returned Value=test_value
Level=2, Returned Value=test_value
Level=3, Returned Value=test_value

然而,事实并非如此。相反,我得到以下信息:

Level=0, Returned Value=test_value
Level=1, Returned Value=([��`�
Level=2, Returned Value=(null)
Level=3, Returned Value=(null)

如果有人能向我解释为什么我只能在我进行插入的递归级别检索哈希表中插入的值,我将不胜感激。

谢谢!

丹尼尔

最佳答案

来自fine manual :

Note that neither keys nor values are copied when inserted into the GHashTable, so they must exist for the lifetime of the GHashTable.

这意味着:

g_hash_table_insert(htable,&key[0],&value[0]);

不复制keyvalue,哈希表只存储指针。但是,keyvalue 分配在堆栈上:

char key[] = "test_key";
char value[] = "test_value";

因此您的&key[0]&value[0] 指针仅在函数运行期间有效。一旦退出递归,您就会得到一个充满无效指针的哈希表,这会给您带来一堆垃圾和未定义的行为。

你应该使用 g_hash_table_new_full具有键和值的释放函数,然后在调用 g_hash_table_insert 时复制键和值;你可以使用 g_strdup复制键和值以及 g_free作为 g_hash_table_new_fullkey_destroy_funcvalue_destroy_func 参数。

关于c - 递归中的 g_hash_table_lookup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7015894/

相关文章:

C 套接字 - 连续读/写,会发生什么?

c - C 中字符串替换多次出现

c++ - 建议将 cpp 代码转换为 UML 类图的工具

linux - 作为内置驱动程序构建时,驱动程序不工作

c - 将虚拟结构或 union 传递给 C 中的函数

c - 打印二叉树时无限循环

c - 接收到的缓冲区包含带有一些垃圾值的实际数据

linux - 返回参数内的字符串 sed/grep/awk/gawk

c - 无法在 C、Linux 中重新打开文件

python - 如何让我的自定义 shell 与 ssh 一起工作?