gpt4 book ai didi

c - 未初始化的值是由堆分配创建的

转载 作者:太空狗 更新时间:2023-10-29 14:54:00 24 4
gpt4 key购买 nike

我正在尝试使用哈希表实现一个单词字典,因此我需要将其设置为全局的,并在我的一个头文件中声明它

extern node** dictionary;

节点在哪里

typedef struct node
{
char* word;
struct node* next;
} node;

然后在另一个定义了函数的文件中,我包含了具有字典声明的标题,并且我还在顶部添加了

node** dictionary;

然后在实际加载字典的函数中,我首先为将构成哈希表的链表分配内存

bool load(const char* dict_file)
{
dictionary = malloc(sizeof(node*) * LISTS);

FILE* dict = fopen(dict_file, "r");

if(dict == NULL)
return false;

char buffer[MAX_LEN + 2];

size_dict = 0;

while(fgets(buffer, MAX_LEN + 2, dict) != NULL)
{
node* new_node = malloc(sizeof(node));

int len = strlen(buffer);

new_node->word = malloc(sizeof(char) * (len));

//avoid \n
for(int i = 0; i < len - 1; i++)
new_node->word[i] = buffer[i];

new_node->word[len - 1] = '\0';

new_node->next = NULL;

int index = hash(buffer);

new_node->next = dictionary[index];

dictionary[index] = new_node;

size_dict++;
}

if (ferror(dict))
{
fclose(dict);
return false;
}

fclose(dict);
return true;
}

所以程序工作正常,然后我释放所有分配给字符串和节点的内存,当我运行 valgrind(检测内存泄漏的调试器)时,它说不可能有内存泄漏,但它说有一个错误 < i>Uninitilised value was created by a heap allocation 并将我重定向到我正在为 dictionary 分配内存的那一行,我在上面写的加载函数的第一行.
我做错了什么?我想我在全局范围内使用 dictionary 的方式是错误的,所以有人可以建议一些其他方法来保持它的全局性并避免这个错误吗?

最佳答案

在更新的代码中,您使用了一个未初始化的指针:

dictionary = malloc(sizeof(node*) * LISTS);

// .... code that does not change dictionary[i] for any i

new_node->next = dictionary[index]; // use uninitialized pointer

正如人们已经写过的,只有当您在进入此循环之前将所有指针都预设为 NULL 时,这才会起作用:

dictionary = malloc(sizeof(node*) * LISTS);
if ( !dictionary ) {
return false;
}

for (size_t i = 0; i < LISTS; ++i) {
dictionary[i] = NULL;
}

关于c - 未初始化的值是由堆分配创建的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27594992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com