C 检查指针数组中的指针是否为空

C 检查指针数组中的指针是否为空,c,arrays,pointers,memory,C,Arrays,Pointers,Memory,我试图检查指针数组中的指针是否为空。程序运行时崩溃,debbugger指向if()条件,但我不知道它出了什么问题 在main.c中 unsigned int** memory = malloc(sizeof(unsigned int*)*MEMORY_SIZE); /* malloc failed */ if (!memory) { return EXIT_FAILURE; } Process myProcess = { 1, 2,

我试图检查指针数组中的指针是否为空。程序运行时崩溃,debbugger指向
if()
条件,但我不知道它出了什么问题

main.c中

  unsigned int** memory = malloc(sizeof(unsigned int*)*MEMORY_SIZE);

    /* malloc failed */
    if (!memory)
    {

       return EXIT_FAILURE;
    }

    Process myProcess = { 1, 2, -1};

    /* TEST THAT WORKS */
    /* memory[0] = &(myProcess.m_id); */
    /* printf("%u", *memory[0]); */


    AllocFirstFit(&myProcess, memory);
在另一个
.c
文件中

void AllocFirstFit(Process* process, unsigned int** memory)
{
    unsigned int itr_mry;
    /* Declaration of various other local variable here*/

    /* browsing the memory */
    for(itr_mry = 0; itr_mry < MEMORY_SIZE; ++itr_mry)
    {
        /* if memory unit is null */
        /* debugger point this line. This condition is never true for some reason */ 
        if(memory[itr_mry] == NULL)
        {
void AllocFirstFit(进程*进程,无符号整数**内存)
{
未签署的国际贸易协定;
/*在此声明各种其他局部变量*/
/*浏览内存*/
用于(itr_mry=0;itr_mry<内存大小;++itr_mry)
{
/*如果内存单元为空*/
/*调试器指向此行。由于某些原因,此条件永远不会为真*/
if(内存[itr\u mry]==NULL)
{

在您的代码中,当
malloc()
ing
memory
时,您为变量
memory
分配了一些内存。您从未初始化
*memory
memory[i]
的内容。它们可能不像您期望的那样为
NULL
。它们很可能包含垃圾值

所以基本上以后,

 if(memory[itr_mry] == NULL)
试图使用未初始化的内存,这会导致错误


解决方案:您需要使用
calloc()
获得零初始化内存,这样您至少可以在代码中的
*内存
内存[i]

上运行空检查,而
malloc()
ing
memory
,您为变量
memory
分配了一些内存。您从未初始化
*memory
memory[i]
的内容。它们可能不像您期望的那样为
NULL
。它们很可能包含垃圾值

所以基本上以后,

 if(memory[itr_mry] == NULL)
试图使用未初始化的内存,这会导致错误


解决方案:您需要使用
calloc()
获得零初始化内存,这样您至少可以对
*内存
内存[i]运行空检查

您需要初始化数组
内存的内容以使自己为空:编译器不会在
malloc
调用中为您执行此操作。当前程序的行为未定义,因为您正在读回未初始化的指针值


最好的做法是使用
calloc
,它将指针设置为空指针值。

您需要初始化数组
内存的内容以自己为空:编译器不会在
malloc
调用中为您执行此操作。当前,由于您正在读回uni,程序的行为未定义初始化指针值


最好的方法是使用
calloc
,它将指针设置为空指针值。

啊,谢谢,我没有注意。我使用了calloc,条件正在工作,只是查找。啊,谢谢,我没有注意。我使用了calloc,条件正在工作,只是查找。啊,谢谢,我没有注意。我使用了calloc和co条件正在发挥作用。谢谢你,我没有注意。我使用了calloc,条件正在发挥作用