gpt4 book ai didi

c - 如何在 C 中正确分配结构数组 HashMap 中的项

转载 作者:行者123 更新时间:2023-11-30 16:13:12 25 4
gpt4 key购买 nike

在下面的代码中,我使用 malloc 将新项目添加到 HashMap 中。我以为我已经检查了所有正确使用 malloc 的框,但 valgrind 说我在它们上出现了内存泄漏。有人能指出我哪里出错了吗?

#include <stdlib.h>
#include <string.h>

typedef struct node
{
char content[46];
struct node* next;
}
node;

typedef node* hashmap_t;

int main (int argc, char *argv[]) {

hashmap_t hashtable[1000];

node *n = malloc(sizeof(node));
if(n == NULL) return 0;

hashmap_t new_node = n;

new_node->next = malloc(sizeof(node));
if(new_node->next == NULL) {
free(n);
return 0;
}

strncpy(new_node->content, "hello", 45);
hashtable[10] = new_node;

for(int y=0; y < 1000; y++) {
if(hashtable[y] != NULL) {
free(hashtable[y]->next);
free(hashtable[y]);
}
}

return 1;
}

最佳答案

对于线路

if(hashtable[y] != NULL)

您没有将hashtable初始化为任何值,并且它也被声明为局部变量。初始值应该是一些垃圾值。因此,您不能假设对于数组的所有 1000 个元素,hashtable[y] 均应为 NULL

您可以在声明时将结构初始化为零

hashmap_t hashtable[1000] = {0};

或者您可以将其声明为全局变量。

关于c - 如何在 C 中正确分配结构数组 HashMap 中的项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58109165/

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