作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在下面的代码中,我使用 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/
我是一名优秀的程序员,十分优秀!