nikhil nanal nikhil nanal - 4 months ago 11
C Question

Segmentation fault in assigning value to a dynamic array of Nodes, inside a structure

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.
Thank you

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

Answer

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