realloc 在缩小动态数组时返回 NULL

问题描述

函数 nodeOutputDel 旨在删除 output[] 元素之一,将其替换为最后一个,并使用 realloc 缩小数组,但 realloc 返回 {{1} } 并且程序以 NULL 退出

errorlevel 11

为什么这不起作用?我当然没有用完内存。

编辑:谢谢,我忘记了当最后一个元素消失时 struct Node { unsigned int *input; unsigned int *output; unsigned int inputCount; unsigned int outputCount; unsigned int id; bool state; }; void nodeOutputDel(struct Node *node,unsigned int id) { unsigned int *newMem,i; for(i = 0; i < node->outputCount; i++) { if(node->output[i] == id) { node->output[i] = node->output[node->outputCount - 1]; node->outputCount--; newMem = realloc(node->output,node->outputCount * sizeof(id)); if(newMem == NULL) exit(11); node->output = newMem; } } } 返回 realloc

解决方法

看起来您正在从数组中删除一项,但您需要将所有内容移到数组中该元素右侧,左侧一个元素。使用 memmove 为您完成繁重的工作。

例如,如果您的节点->输出数组是 [11,22,33,44],并且您想从中删除 22,您希望将该数组的大小调整为 [11,44]。>

取而代之的是:

    if(node->output[i] == id)
    {
        node->output[i] = node->output[node->outputCount - 1];
        node->outputCount--;
        newMem = realloc(node->output,node->outputCount * sizeof(id));
        if(newMem == NULL) exit(11);
        node->output = newMem;
    }

这个:

    if(node->output[i] == id)
    {
        // shift all the nodes to right of node->output[i] one slot to the left

        unsigned int shift = node->outputCount - i - 1;
        
        if (shift > 0)
        {
            memmove(node->output+i,(node->output)+(i+1),shift*sizeof(id));
        }
        node->outputCount--;

        if (node->outputCount == 0)
        {
           free(node->output);
           node->output = NULL;
        }
        else
        {
            node->output = realloc(node->output,node->outputCount * sizeof(id));
        }
    }