【问题标题】:check if pointer is null in a pointer array检查指针数组中的指针是否为空
【发布时间】:2015-12-16 09:51:17
【问题描述】:

我正在尝试检查指针数组中的指针是否为 NULL。运行时程序崩溃,调试器指向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)
        {

【问题讨论】:

    标签: c arrays pointers memory


    【解决方案1】:

    您需要自己将数组memory 的内容初始化为NULL:编译器不会在malloc 调用中为您执行此操作。目前你的程序的行为是未定义的,因为你正在读回一个未初始化的指针值。

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

    【讨论】:

    • 啊谢谢,我没注意。我使用了 calloc 并且条件正在起作用,只需找到
    【解决方案2】:

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

    所以,基本上,以后,

     if(memory[itr_mry] == NULL)
    

    尝试使用未初始化的内存,导致undefined behavior

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

    【讨论】:

    • 啊谢谢,我没注意。我使用了 calloc 并且条件正在起作用,只需找到。
    猜你喜欢
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多