I'm new to valgrind and I ran it with some code I wrote for a quadtree.
I've written a function that recursively frees the Nodes from the quadtree:
void destroyTree (Node* p)
{
if (!p) return;
for (size_t i = 0; i < 4; ++i)
destroyTree(p->child[i]);
free(p);
}
I call that function in the main function:
int main( int argc, char **argv ) {
Node *head;
// make the head node
head = makeNode( 0.0,0.0, 0 );
// make a tree
makeChildren( head );
makeChildren( head->child[0] );
makeChildren( head->child[1] );
makeChildren( head->child[2] );
makeChildren( head->child[3] );
// print the tree for Gnuplot
writeTree( head );
return 0;
//destroy tree
destroyTree (head);
return 0;
}
When I run valgrind its showing that I lose some memory.
The structure is:
struct qnode {
int level;
double xy[2];
struct qnode *child[4];
};
typedef struct qnode Node;
I call malloc in buildTree:
Node *makeNode( double x, double y, int level ) {
int i;
Node *node = (Node *)malloc(sizeof(Node));
node->level = level;
node->xy[0] = x;
node->xy[1] = y;
for( i=0;i<4;++i )
node->child[i] = NULL;
return node;
}
How do I stop the leak? Is there something wrong with my freeing function or is it somewhere else?
malloc
call inmakenode
is unfreed. You should share that function. – StoryTeller - Unslander Monicareturn 0
in the middle of your code so destroy function isn't called!! please enable warnings – Jean-François Fabremakenode
, you have a member variable calledxy
that appears to be either an array or pointer. How are you allocating space for that, and likewise, how are you freeing it? Before you free a node, you also have to free any pointers inside of it, first. – Alex Reynoldsreturn 0
but that didn't make a difference – anon2000