对于一个项目,我正在学习在 c 中使用 malloc/realloc,但我无法弄清楚为什么这段代码会给我一个段错误!
#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);
在尝试了一堆东西并搜索了 stackoverflow 之后,我真的陷入了想法!任何信息都有帮助!
谢谢
编辑:
感谢您的帮助!但我在程序的后面仍然遇到段错误,可能是因为类似的错误,但我已经尝试了很多东西但无法让它工作,这是我所有的 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 或类似的东西?
谢谢
最佳答案
- 你不需要所有这些类型定义
- 你不需要施法
sizeof *ptr
给出ptr
指向 的对象 的大小
- 恕我直言,没有 casts 和 typedef 的代码更清晰:
#include <stdlib.h>
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;
}
关于c - Malloc 语句给出段错误 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39872405/