[英]How to properly malloc item in struct array hashmap in C
在以下代码中,我使用 malloc 向 hashmap 添加新项目。 我以为我已经检查了所有框以正确使用 malloc,但 valgrind 说我有 memory 泄漏。 有人可以指出我哪里出错了吗?
#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};
或者您可以将其声明为全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.