如何在C中正确分配结构数组哈希图中的项目 [英] How to properly malloc item in struct array hashmap in C

查看:77
本文介绍了如何在C中正确分配结构数组哈希图中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,我正在使用malloc将新项目添加到哈希图中.我以为我已经检查了所有使用malloc的框,但是valgrind说我的内存泄漏.有人可以指出我出了问题的地方吗?

In the following code, I'm using malloc for adding a new item to a hashmap. I thought I've checked all the boxes for properly using malloc, but valgrind says I've got a memory leak on them. Can someone point me to where I've gone wrong?

#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.

You do not initialise hashtable to any value and it is also declared as a local variable. The initial value shall be some garbage value. So you cannot assume that if hashtable[y] shall be NULL for all 1000 elements of the array.

您可以在声明例如

hashmap_t hashtable[1000] = {0};

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

or you can declare it as a global variable.

这篇关于如何在C中正确分配结构数组哈希图中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆