How to properly malloc item in struct array hashmap in C

こ雲淡風輕ζ 提交于 2020-01-16 09:11:30

问题


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;
}

回答1:


For the line

if(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.

You can initialize the structure to zero while declaring e.g.

hashmap_t hashtable[1000] = {0};

or you can declare it as a global variable.



来源:https://stackoverflow.com/questions/58109165/how-to-properly-malloc-item-in-struct-array-hashmap-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!