函数内部内存重新分配时出错

问题描述 投票:0回答:1

我编写了一个函数,将指向对象的指针追加到数组中,但是当从嵌套函数调用它时,

realloc
无法正确重新分配内存。然而,当我从函数重新分配内存时,之前已经分配了对象,一切都很好

这是我的代码的简化示例:

#include <stdlib.h>

typedef struct Node
{
    char ch;
    int freq;
    struct Node *left, *right;

} Node;

Node *newNode(char ch, int freq, Node *left, Node *right)
{
    Node *node = (Node *)malloc(sizeof(Node));
    node->ch = ch;
    node->freq = freq;
    node->left = left;
    node->right = right;

    return node;
};

void pushNode(Node **nodes, Node *node, int *nodesCount)
{
    nodes = (Node **)realloc(nodes, ++(*nodesCount) * sizeof(Node *)); // error
    nodes[*nodesCount - 1] = node;
}

int main()
{
    int nodesCount = 0;
    Node **nodes = (Node **)calloc(0, sizeof(Node *));

    Node *node = newNode('\0', 0, NULL, NULL);
    // pushNode(nodes, node, &nodesCount);
    nodes = (Node **)realloc(nodes, ++nodesCount * sizeof(Node *)); // no error
    nodes[nodesCount - 1] = node;

    return 0;
}
c memory-management realloc
1个回答
0
投票

您的错误来自

nodes
,它是
pushNode
函数的本地函数,您应该有类似的内容:

void pushNode(Node ***nodes, Node *node, int *nodesCount)
{
    Node **newNodes;
    newNodes = (Node **)realloc(*nodes, ++(*nodesCount) * sizeof(Node *));
    /* check newNodes */
    *nodes = newNodes
    (*nodes)[*nodesCount - 1] = node;
}
© www.soinside.com 2019 - 2024. All rights reserved.