Reputation: 800
I am unsure what it is I am doing wrong when initialising this hash table. Can anyone help? I am getting a segfault at the initialisation of the bucket list in the for loop, where I have labelled it.
#define BUCKETMAX 20
#define TABLESIZE 100
//Node to hold entry
typedef struct node{
MEntry *entry;
struct node *next;
}MListNode;
//Bucket linked list to hold Nodes
typedef struct bucket{
int size;
MListNode *top;
}BucketList;
//Hash table to hold Bucket Lists
typedef struct mlist{
int capacity;
BucketList **bList;
}MList;
MList *ml_create(void){
//Initialising the hash table
MList *ml;
//Check if memory if available to be allocated before assigning capacity
if((ml = (MList *) malloc(sizeof(BucketList **) * TABLESIZE)) == NULL){
fprintf(stderr, "Hash Table Could Not be Created (Not Enough Memory)\n");
exit(EXIT_FAILURE);
}else{
ml->capacity = TABLESIZE;
//Initialise the bucket lists
int i;
for(i =0; i<TABLESIZE;i++){
/****************************************************************
SEGFAULT IS HERE */
if((ml->bList[i] = (BucketList *) malloc(sizeof(MListNode *) * BUCKETMAX)) == NULL){
/****************************************************************/
fprintf(stderr, "Bucket List Could Not be Created (Not Enough Memory)\n");
exit(EXIT_FAILURE);
}else{
ml->bList[i]->size = 0;
ml->bList[i]->top = (MListNode *) NULL;
}
}
}
return ml;
}
Any help would be appreciated, thanks.
Upvotes: 0
Views: 94
Reputation: 6293
You cannot allocate memory for structures the way you do.
ml = (MList *) malloc(sizeof(BucketList **) * TABLESIZE)
That line allocates memory to the MList
structure ml
, but not to its member ml->bList
which you are then filling in the loop at the point of the segfault.
You need to allocate memory for both purposes separately:
ml = malloc(sizeof(MList));
ml->bList = malloc(sizeof(BucketList*) * TABLESIZE);
The same applies to the latter memory allocation for ml->bList[i]
.
Upvotes: 1