【发布时间】:2017-02-13 19:21:13
【问题描述】:
对于一个我正在学习在 c 中使用 malloc/realloc 的项目,但我无法弄清楚为什么这段代码会给我一个 seg 错误!
#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 或类似情况?
谢谢
【问题讨论】:
-
index_data_t *index_data=NULL; index_data->index_data_array = ...所以NULL->index_data_array -
malloc()极不可能导致段错误。这里的问题是你取消引用index_data,这是一个空指针 -
在你的 sizeof() 中,你试图访问 index_data,它在前面的语句中被标记为 NULL。
-
@hashdefine
sizeof的参数未计算,因此允许在其中取消引用 null
标签: c segmentation-fault malloc