C- malloc阵列,有条件的跳跃在非初始化的值上



我正在使用malloc创建一系列指针。但是,每当我尝试在数组中的一个索引中引用某些内容时,我正在收到阀条件跳跃或移动取决于非初始化的值。在我的代码中,有时会在索引上存储一些东西,有时不会。例如,可能有一个指针存储在值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
}
}

我的目标是能够确定是否存储在索引

分配指针 - 阵列在使用之前将其设置为所有NULL s:

for (size_t i = 0; i < sizeHint; ++i)
{
  arrayOfPointers[i] = NULL;
}

malloc()不为您执行此操作。

来自C11标准(草稿)7.22.3.4/2:

malloc函数分配空间的大小由大小指定的对象,并且 其价值不确定。

通过malloc分配后,内存将不会自动初始化为NULL(或其他任何内容)。它仍然可以包含任何东西,这就是为什么Valgrind警告您有关比较的原因。

将整个分配初始化为0(至少被GCC,Clang和MSVC视为NULL),您可以使用:

memset(arrayOfPointers, 0, sizeHint * sizeof(Entry*));

MEMSET功能由string.h标头文件提供。

最新更新