title: Getting memory leak when combining Vala with C
body: <p>The following Vala code combined with C is causing memory leaks and I can't wrap my head around it.</p>
  
  <p><strong>Main.vala</strong></p>
  
  <pre><code>using GLib;
  
  [CCode (cname = "c_function")]
  public static extern void c_function (out Tree&lt;int, Tree&lt;int, string&gt;&gt; tree);
  
  public static int main () {
  
      Tree&lt;int, Tree&lt;int, string&gt;&gt; tree;
      c_function (out tree);
      // If code were to end here and return 0, no memory leak happens, but
      // if we call c_function again, memory leak happens according to valgrind
      c_function (out tree); // Leak happens on this second call
      return 0;
  }
  </code></pre>
  
  <p><strong>main.c</strong></p>
  
  <pre><code>#include &lt;glib.h&gt;
  
  gint treeCompareFunction (gint a, gint b);
  
  void extern c_function (GTree **tree) {
      *tree = g_tree_new ((GCompareFunc)treeCompareFunction);
  
      for (int i = 0; i &lt; 3; i++) {
          // Memory leak in the next line when function is called a second time
          GTree * nestedTree = g_tree_new ((GCompareFunc)treeCompareFunction); 
          g_tree_insert (nestedTree, i, "value 1");
          g_tree_insert (*tree, i, (gpointer) nestedTree);
      }
  }
  
  gint treeCompareFunction (gint a, gint b) {
      if (a &lt; b) return -1;
      if (a == b) return 0;
      return 1;
  }
  </code></pre>
  
  <p>I don't understand why if I call the C function only once no memory leak happens, but if I call it a second time, <strong>line 10</strong> of <strong>main.c</strong> which creates a Tree in a for loop causes a memory leak.</p>
  
  <p>The code is compiled with </p>
  
  <pre><code>valac Main.vala main.c -g
  </code></pre>
  
  <p>And then run with </p>
  
  <pre><code>valgrind --leak-check=yes ./Main
  </code></pre>
  
  <p>I would like to know if it is possible to work around it. I tried emptying the tree in the Vala code before calling the C function for the second time. No success. Also tried destroying the tree passed as argument if it wasn't NULL on the second call of the C function. No success either. Still getting memory leaks.</p>