Valgrind正在抱怨一种方法,我真的无法弄清楚原因。我得到的错误信息如下:
==1664== Uninitialised value was created by a heap allocation
==1664== at 0x47F1: malloc (vg_replace_malloc.c:302)
==1664== by 0x100004B6A: filter_my_struct_list (main.c:3357)
==1664== by 0x100002C7C: main (main.c:370)
在方法中,他抱怨我只是想"压缩"一个列表,意思是,我将我的结构的连续元素合并为一个。
my_struct只是一个包含两个int值的结构:
typedef struct {
int start;
int len;
} my_struct;
方法如下:
my_struct* filter_my_struct_list(my_struct *listl, int *elements_in_list) {
my_struct *compressed_list;
if (*elements_in_list == 0) {
fprintf(stderr, "Number of my_structs should not be zero! Please check the input!\n");
exit(1);
} else if (*elements_in_list == 1) {
compressed_list = malloc(sizeof(my_struct)* 1);
my_struct f = {listl[0].start, listl[0].len};
compressed_list[0] = f;
return compressed_list;
}
int fst, remained_index;
remained_index = fst = 0;
compressed_list = malloc(sizeof(my_struct) * (*elements_in_list)); //<== The line valgrind doesn't like
while (fst < (*elements_in_list - 1)) {
int fst_in_loop = fst;
int nxt = fst_in_loop + 1;
BOOL terminate = FALSE;
while (!terminate) {
if (((listl[fst_in_loop].start + listl[fst_in_loop].len) == listl[nxt].start)) {
fst_in_loop++;
nxt++;
} else terminate = TRUE;
if (nxt == (*elements_in_list)) {
terminate = TRUE;
}
}
if (fst_in_loop != fst) {
int new_len = listl[fst_in_loop].start
+ listl[fst_in_loop].len - listl[fst].start;
my_struct f = {listl[fst].start, new_len};
compressed_list[remained_index] = f;
} else {
my_struct f = {listl[fst].start, listl[fst].len};
compressed_list[remained_index] = f;
}
remained_index++;
fst = nxt;
if (nxt == (*elements_in_list - 1)) {
if (fst == fst_in_loop) {
int f_1;
for (f_1 = fst; f_1 <= nxt; f_1++) {
my_struct f = {listl[f_1].start, listl[f_1].len};
compressed_list[remained_index] = f;
remained_index++;
}
} else {
my_struct f = {listl[nxt].start, listl[nxt].len};
compressed_list[remained_index] = f;
remained_index++;
}
}
}
*elements_in_list = remained_index;
return compressed_list;
}
为什么他告诉我它没有被初始化,因为我抓住的情况是少于两个要合并的元素?
编辑:
好的,我发现,当我只调用此方法时,错误消失,但是一旦我重复使用我的列表,就会出现错误