For a project I am learning to use malloc/realloc in c, but I cannot figure out why this code gives me a seg fault!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef struct word_data word_data_t;
typedef struct data data_t;
typedef struct index_data index_data_t;
struct word_data {
int docunumber;
int freq;
};
struct data {
char *word;
int total_docs;
word_data_t *data;
};
struct index_data {
data_t *index_data_array;
};
/* Inside a function called from main */
index_data_t *index_data=NULL;
index_data->index_data_array = (data_t*)malloc(sizeof(*(index_data- >index_data_array))*INITIAL_ALLOCATION);
Im seriously stuck for ideas after trying a bunch of stuff and searching stackoverflow! any info helps!
Thanks
EDIT:
Thanks for your help guys! but im still running into a seg fault later in the program, probably because of a similar mistake, but I've tried a bunch of stuff and cant get it to work, here are all my malloc/realloc calls:
index_data = (index_data_t*)malloc(sizeof(*index_data)*INITIAL_ALLOCATION);
index_data->index_data_array = (data_t*)malloc(sizeof(*index_data- >index_data_array)*INITIAL_ALLOCATION);
index_data->index_data_array = realloc(index_data->index_data_array, current_size_outer_array*sizeof(*(index_data->index_data_array)))
index_data->index_data_array[index].word=malloc(strlen(word)+1);
index_data->index_data_array[index].word=entered_word;
index_data->index_data_array[index].data = (word_data_t *)malloc(sizeof(word_data_t)*INITIAL_ALLOCATION);
index_data->index_data_array[index].total_docs=atoi(word);
index_data->index_data_array[index].data = realloc(index_data- >index_data_array[index].data, current_size_inner_array*(sizeof(*(index_data- >index_data_array[index].data))))
index_data->index_data_array[index].data->docunumber = docunum;
index_data->index_data_array[index].data->freq = freq;
then when I go to print out something later:
printf("%d\n", index_data->index_data_array[0].total_docs);
I get a segfault, have I missed a malloc again or similar?
Thanks