poke
poke

Reputation: 387497

Tracking down a memory leak with Valgrind

According to Valgrind, I have a rather big memory leak in my program, but I actually don’t think that is the case. Or maybe I’m just unaware of something. I am using Valgrind for the very first time, so I might be interpreting it wrong, or possibly taking it too seriously.

Anyway, Valgrind is telling me that ~13 MB (56 bytes direct, the rest indirect) are definitely lost. The code in question looks like this:

Node* newRoot = malloc(sizeof(Node));
newRoot->children[0] = tree->root;
newRoot->children[1] = otherNode;
newRoot->k = 2;

tree->root = newRoot;

As you can probably tell, I have a tree structure where the tree object has a single root, and a Node multiple childs. In this part of the code, the tree gets expanded to the top; the old root becomes a child of a new node which then becomes the new root. tree is a Tree*, the root member is a Node pointer, and children is an array of Node pointers.

Now Valgrind tells me that the memory allocated with above’s malloc is lost, but in my understanding, I’m pointing to that memory block from the new root while the old root is kept as a child of the new root.

At the end of my program, I’m recursively freeing the memory of all nodes in the tree (by recursively descending into all children, starting at root), so I’m pretty sure that the memory is ultimately freed.

Am I missing something? Is there a way to get more detailed information from Valgrind to find out what exactly is (not) happening?

Upvotes: 1

Views: 4191

Answers (1)

Kiril Kirov
Kiril Kirov

Reputation: 38143

What valgrind's memcheck (the default tool) basically does for monitoring memory leaks is - monitor each memory allocation and whether the allocated memory is freed later. If it's not freed, it shows you where it was allocated, as it cannot show you where it should be freed.

My point is - even if the allocating/add function seems good, we/you should take a look at the freeing function. Most probably, the problem is there, based on the information in your question.

Another thing, that could be useful is: how you run valgrind? I use the following options:

valgrind --trace-children=yes --track-fds=yes --log-fd=2 --error-limit=no \
         --leak-check=full --show-possibly-lost=yes --track-origins=yes \
         --show-reachable=yes executable executable_arguments_if_any

Sometimes the verbose function can also be useful.

Upvotes: 5

Related Questions