I'm trying to tackle memory leaks more and more in my endeavor to learn this language..
The program I'm working on is a Binary Search Tree, the tree's root is always located at tree->root->l
. Now if I do this...
BSTNode *search(BSTree *tree ,Item elem)
{
BSTNode* aux;
aux = tree->root->l;
/*
* BSTNode not found.
*
*/
if(notFound)
{
free(aux);
free(found)
return NULL;
}
// . . . . . .
}
will it also dealocate tree->root->l
? how do I avoid it if so?
The pointer itself is in automatic storage, which means you don't have to worry about allocating it or freeing it. As such, it's not the pointer you need to be worried about, but the memory addressed by the pointer. This is where free
comes into play. free
doesn't free the pointer, but the memory addressed by the pointer.
will it also dealocate
tree->root->l
?
It will deallocate the memory to which both aux
and tree->root->l
point.
The memory in question is still being used by the tree, so it shouldn't be freed at this time.
how do I avoid it if so?
Remove free(aux);
.
Does this mean that if I leave variables like this it wouldn't cause a memory leak or unnecessarily used recourse?
Correct. The question you need to ask yourself is "is the memory addressed by this pointer still being used?" If the answer is yes, don't free it. If the answer is no, free it.