When I try to use these malloc statements using these structs (these statements aren't all in a row in my actual code but built in to a function that mallocs/reallocs as needed) I believe my problem lies within these statements so I only included those, as I believe I am currently not mallocing correctly in order to get memory to store things in a struct of word_data_t inside an array data in a struct of type data_t inside an array in a struct of type index_data_t:
EDIT: Added compilable code.
#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;
#define INITIAL_ALLOCATION 2
void test();
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;
};
int main(int argc, char const *argv[]) {
test();
return 0;
}
void test() {
/* Inside a function called from main */
char entered_word[4] = "wow";
int docunum = 4, index=0, freq=6, current_size_outer_array=0, current_size_inner_array=0;
int total_docs_in=1, doc_freq_pairs=1;
index_data_t *index_data=NULL;
for (index=0; index<4; index++) {
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);
current_size_outer_array = INITIAL_ALLOCATION;
if (index == 2) {
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(entered_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);
current_size_inner_array = INITIAL_ALLOCATION;
index_data->index_data_array[index].total_docs=total_docs_in;
if (/* Need more data points */ doc_freq_pairs<2) {
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;
}
printf("%d\n", index_data->index_data_array[0].total_docs);
printf("%s\n", index_data->index_data_array[1].word);
printf("%d\n", index_data->index_data_array[1].data->freq);
}
I get a seg fault
, I cant seem to figure out why, what I expect to happen is the 2nd malloc call creates space for index_data->index_data_array[0]
and [1]
, but maybe I need to set aside memory for them another way? this malloc stuff does my head in.
Thanks!