我正在使用Malloc来创建一个指针数组。但是,当我尝试在数组中的某个索引中引用某些内容时,我正在接收valgrind条件跳转或移动取决于未初始化的值。在我的代码中,某些时候会有一些东西存储在索引[]中,有时则不会。例如,可能存在存储在值1,4,6的指针但不存在于任何其他指针中。我的目标是能够确定没有valgrind错误!
typedef struct{
char* symbol;
void* datapointer;
void* nextstruct;
}Entry;
void main(){
int sizeHint = 10000; //size of array
Entry** arrayOfPointers = malloc(sizeHint * sizeof(Entry*));
//For the sake of keeping this simple, say I stored something
//in a bunch of indexes in the array but NOT at 5
if(arrayOfPointers[5] != NULL){
//this is where my error comes, as it reads
//conditional jump or move depends on uninitilised value
//my goal is to be able to determine if something is stored at an index, and
//do something if its not stored
}
}
答案 0 :(得分:2)
我的目标是能够确定某些内容是否存储在索引中
在分配指针数组之后,在使用之前将其设置为所有NULL
:
for (size_t i = 0; i < sizeHint; ++i)
{
arrayOfPointers[i] = NULL;
}
malloc()
不会为您执行此操作。
来自C11标准(草案)7.22.3.4/2:
malloc函数为一个对象分配空间,该对象的大小由size和 其价值是不确定的。
答案 1 :(得分:0)