title: Tracking down a memory leak with Valgrind
body: <p>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.</p>
  
  <p>Anyway, Valgrind is telling me that ~13 MB (56 bytes direct, the rest indirect) are definitely lost. The code in question looks like this:</p>
  
  <pre><code>Node* newRoot = malloc(sizeof(Node));
  newRoot-&gt;children[0] = tree-&gt;root;
  newRoot-&gt;children[1] = otherNode;
  newRoot-&gt;k = 2;
  
  tree-&gt;root = newRoot;
  </code></pre>
  
  <p>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. <code>tree</code> is a <code>Tree*</code>, the <code>root</code> member is a Node pointer, and <code>children</code> is an array of Node pointers.</p>
  
  <p>Now Valgrind tells me that the memory allocated with above’s <code>malloc</code> 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.</p>
  
  <p>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 <code>root</code>), so I’m pretty sure that the memory is ultimately freed.</p>
  
  <p>Am I missing something? Is there a way to get more detailed information from Valgrind to find out what exactly is (not) happening?</p>