Malloc语句给出分段错误11

对于一个项目我正在学习在c中使用malloc / realloc,但我无法弄清楚为什么这段代码给我一个seg错误!

#include  #include  #include  #include  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); 

在尝试了一堆东西并搜索stackoverflow之后,我严重陷入困境! 任何信息帮助!

谢谢

编辑:

谢谢你的帮助! 但是我在程序后期仍然遇到了一个seg故障,可能是因为类似的错误,但我已经尝试了很多东西而且无法让它工作,这里是我所有的malloc / realloc调用:

 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; 

那时候我去打印出来的东西:

 printf("%d\n", index_data->index_data_array[0].total_docs); 

我得到了一个段错误,我是否再次错过了一个malloc或类似的?

谢谢

  • 你不需要所有这些typedef
  • 你不需要施放
  • sizeof *ptr给出ptr 指向对象的大小
  • 恕我直言,没有强制转换和typedef的代码更清晰:

 #include  struct thing { int type; char name[13]; }; struct box { unsigned nthing; struct thing *things; }; struct box *make_box(unsigned thingcount) { struct box *thebox; thebox = malloc (sizeof *thebox); if (!thebox) return NULL; thebox->things = malloc (thingcount * sizeof *thebox->things); if (!thebox->things) { free(thebox); return NULL; } thebox->nthing = thingcount; return thebox; } 

尝试访问来自NULL地址空间的元素。 试试这个 :

 index_data = (index_data_t*)malloc(sizeof(*(index_data))); 

所以,你可以填充你的数组,如:

 index_data->index_data_array = (data_t*)malloc(sizeof(*(index_data->index_data_array))*INITIAL_ALLOCATION);