Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error during memory reallocation inside a function

I wrote a function to append pointer to an object to array, but realloc can’t properly reallocate memory when it’s called from a nested function. However, when I’m reallocating memory from function, where object has been previously allocated, everything is alright

Here is a simplified example of my code:

#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);

    for (int i = 0; i < 256; i++)
    {
        node = newNode((char)i, i, NULL, NULL);
        // pushNode(nodes, node, &nodesCount);
        nodes = (Node **)realloc(nodes, ++nodesCount * sizeof(Node *)); // no error
        nodes[nodesCount - 1] = node;
    }

    free(nodes);

    return 0;
}

Running the code above causes the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

test(94309,0x1ec9f2500) malloc: *** error for object 0x60000020c020: pointer being realloc'd was not allocated
test(94309,0x1ec9f2500) malloc: *** set a breakpoint in malloc_error_break to debug

>Solution :

Your error comes from nodes that is local to pushNode function, you should have something like:

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading