c-Valgrind-使用堆上分配的未初始化值



我正在尝试创建一个指向自定义结构的"指针数组",动态分配内存,因为我不确定这个数组的大小。在初始化数据时,我可以毫无问题地访问每个索引处的自定义结构。

一旦我退出初始化循环,突然valgrind告诉我正在使用大小为8的统一值。我真的不明白为什么会这样。使用calloc将所有内容初始化为null(正如我所料(也没有帮助。使用像FuncSym *f_sym[NB_LINES];这样的指针数组并更改需要更改的内容也没有帮助。我确实认为FuncSym_create(...)会正确初始化所有内容。

...
unsigned long count = 0;
FuncSym **f_sym = (FuncSym**)malloc(NB_LINES * sizeof(FuncSym*));
unsigned long cur_max = NB_LINES;
char *line = NULL;
size_t len = 0;
ssize_t nread;
const char *del = " ";
while((nread = getline(&line, &len, tmp)) != -1) {
if(true) { // make example smaller
if(++count < cur_max) {
f_sym[count] = FuncSym_create("name", 10, 10);
printf("No Problem Here! n Addr: %lu", FuncSym_addr(f_sym[count]));
} else { // make sure size fits
cur_max = 2*cur_max;
FuncSym **tmp = (FuncSym**)realloc(f_sym, cur_max*sizeof(FuncSym*));
if(!tmp){
for(unsigned long i = 0; i < count; i++)
FuncSym_free(f_sym[i]);
free(f_sym);
exit(EXIT_FAILURE);
}
f_sym = tmp;
f_sym[count] = FuncSym_create("name", 10, 10);
}
}
}
for(unsigned long i = 0; i <= count; i++){
printf("Unitialised value here: %lunn", FuncSym_addr(f_sym[i]));
}
...
struct FuncSym {
char *name;
unsigned long addr;
unsigned long size;
};
FuncSym *FuncSym_create(char *sym_name, unsigned long addr, unsigned long size){
assert(sym_name != NULL);
FuncSym *f_sym = (FuncSym*)malloc(sizeof(FuncSym));
if(!f_sym) stack_mem_error();
f_sym->name = strdup(sym_name);
f_sym->addr = addr;
f_sym->size = size;
return f_sym;
}
unsigned long FuncSym_addr(FuncSym *f_sym) { return f_sym->addr; }
从未设置

f_sym[0],因为在输入if语句之前计数器已递增(++counter(。当后来访问f_sym[0]时,它确实未初始化。修复计数器解决了所有问题。以防有人读到这个问题。

...
while((nread = getline(&line, &len, tmp)) != -1) {
if(true) { // make example smaller
if(count+1 < cur_max) {
f_sym[count++] = FuncSym_create("name", 10, 10);
printf("No Problem Here! n Addr: %lu", FuncSym_addr(f_sym[count]));
} else { // make sure size fits
cur_max = 2*cur_max;
FuncSym **tmp = (FuncSym**)realloc(f_sym, cur_max*sizeof(FuncSym*));
if(!tmp){
for(unsigned long i = 0; i < count; i++)
FuncSym_free(f_sym[i]);
free(f_sym);
exit(EXIT_FAILURE);
}
f_sym = tmp;
f_sym[count++] = FuncSym_create("name", 10, 10);
}
}
}
...

相关内容

  • 没有找到相关文章

最新更新