Search code examples
carrayshashmapmallocvalgrind

How to properly malloc item in struct array hashmap in C


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

Solution

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