Reputation: 543
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:
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
Upvotes: 0
Views: 108
Reputation: 9659
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;
}
Upvotes: 1