如何在 C 中正确地 malloc struct array hashmap 中的项目

How to properly malloc item in struct array hashmap in C

在下面的代码中,我使用 malloc 将新项目添加到哈希图中。我以为我已经检查了所有正确使用 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 初始化为任何值,它也被声明为局部变量。初始值应该是一些垃圾值。所以你不能假设 if hashtable[y] 应该是 NULL 对于数组的所有 1000 个元素。

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

hashmap_t hashtable[1000] = {0};

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