Reputation: 689
I'm having some problems setting a pointer within a structure to NULL. I'm getting a segimtation fault. What is causing this and how can I fix it?
typedef struct data_{
void *data;
struct data_ *next;
}data_el;
typedef struct buckets_{
char *key;
data_el *head_data_p;
}buckets;
typedef struct hash_table_ {
/* structure definition goes here */
int (*hash_func)(char *);
int (*comp_func)(void*, void*);
buckets **buckets_array;
} hash_table, *Phash_table;
int i,size;
size = 10;
table_p -> buckets_array = (buckets **)malloc(sizeof(buckets)*(size+1));
for(i = 0; i < size; i++){
/*Getting segmitation falut here*/
table_p -> buckets_array[i] -> key = NULL;
table_p -> buckets_array[i] -> head_data_p = NULL;
Upvotes: 0
Views: 264
Reputation: 67345
Because you aren't initializing buckets_array
. So the pointers don't yet point to anything and you get an error when you try and modify what they point to.
You need to initialize your array of pointers, and also each individual pointer:
table_p -> buckets_array = malloc(sizeof(buckets *) * (size+1));
for(i = 0; i < size; i++) {
table_p -> buckets_array[i] = malloc(sizeof(bucket));
table_p -> buckets_array[i] -> key = NULL;
table_p -> buckets_array[i] -> head_data_p = NULL;
}
Upvotes: 2
Reputation: 7996
You should replace:
buckets **buckets_array;
With:
buckets *buckets_array;
And:
(buckets **)malloc(sizeof(buckets)*(size+1));
With:
(buckets *)malloc(sizeof(buckets)*(size+1));
And also:
table_p -> buckets_array[i] -> key = NULL;
table_p -> buckets_array[i] -> head_data_p = NULL;
With:
table_p -> buckets_array[i] . key = NULL;
table_p -> buckets_array[i] . head_data_p = NULL;
Upvotes: 1