0

I am trying to create a Hash Map in C. Below is the code. When I try to assign value to the elements of Darray ( each of which is a pointer to a Node) I am getting a segmentation fault ( i.e. at line 23 and24). Could anybody help in pointing out where am I going wrong.

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* next;
}Node;

typedef struct Map{
    struct Node** Darray;
} Map;

#define SIZE 10
int main()
{
    int i=0;
    Map* M = malloc(sizeof(Map));
    M->Darray = (struct Node**)malloc(sizeof(Node*)*SIZE);
    for (i =0;i < SIZE;i++){
        M->Darray[i]->data =0;
        M->Darray[i]->next =NULL;
    }
}
Serenity
  • 35,289
  • 20
  • 120
  • 115
  • 1
    Fyi, dynamic allocation of `Map` is unnecessary here. And somewhere in `Map` should be the magnitude of the `Node` pointer array, or you're going to find expansion, reduction, and rehashing when load factors are ascended impossible. Finally, [don't cast `malloc()` and friends in C programs](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – WhozCraig Jul 30 '16 at 19:28

1 Answers1

1

You allocate space for SIZE pointers to Node, but don't initialize these in any way, so when you access M->Darray[i] in M->Darray[i]->data you get segmentation fault because value of M->Darray[i] has not been set.

You need to allocate space for each node before using it:

for (i = 0; i < SIZE; i++) {
    M->Darray[i] = malloc(sizeof(Node));
    M->Darray[i]->data = 0;
    M->Darray[i]->next = NULL;
}

Depending on your needs, you could also change Darray to be an array of nodes instead of node pointers, so you can allocate space for all nodes at once:

struct Node* Darray;
...
M->Darray = malloc(sizeof(Node) * SIZE);
for (i = 0; i < SIZE; i++) {
    M->Darray[i].data = 0;
    M->Darray[i].next = NULL;
}
Markus Laire
  • 2,837
  • 2
  • 17
  • 23