title: How to free allocated memory in a binary tree in C
body: <p>I am having trouble with a function in my C program.  The purpose of the program is to:  </p>
  
  <ul>
  <li>Read integers from a binary file into an array</li>
  <li>Sort these numbers using a binary tree</li>
  <li>Do some other stuff </li>
  <li>Free all memory that you allocated using malloc();</li>
  </ul>
  
  <p>I've got everything working except for being able to free my binary tree.  Here are my structures for the tree and node (a.k.a. leaf).</p>
  
  <pre><code>typedef struct Node *NodeP;
  typedef struct Tree *TreeP;
  
  // Definition of a tree
      struct Tree
      {
          NodeP root;
      }Tree;
  
      // Definition of a node
      struct Node
      {
          int data;
          NodeP L, R;
      }Node;
  </code></pre>
  
  <p>In my program, I have used malloc to allocate memory for my tree and for each individual node.  So I call a function to free the tree and all of its nodes.</p>
  
  <pre><code>/*
   * Frees the memory allocated for
   * each node
   */
  void freeNode(NodeP p)
  {
      if(p == NULL) return;
      freeNode(p-&gt;L);
      freeNode(p-&gt;R);
      free(p);
  }
  
  /*
   * Frees the memory allocated
   * for the tree
   */
  TreeP freeTree(TreeP tree)
  {
      if(tree-&gt;root == NULL)
          free(tree);
      else
      {
          freeNode(tree-&gt;root);
          free(tree);
      }
  
      return NULL;
  }
  </code></pre>
  
  <p>When I run this program, my debugger is giving me this error.</p>
  
  <pre><code>EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
  </code></pre>
  
  <p>I've tried mentally going through each iteration of the recursion, and I can't find why it's giving me an error.  I'm thinking it's falling off the edge of the tree at the edge cases?  I'm not sure.  Any help is greatly appreciated!</p>
  
  <p>EDIT:</p>
  
  <p>Here is a link to download the full program.  I included a README and the binary files I am working with.  One is only 10 integers in length, the other is 20000 in length.  Thanks for your help so far!</p>
  
  <p><a href="https://copy.com/902v0bMv8DtIMUrc" rel="nofollow">https://copy.com/902v0bMv8DtIMUrc</a></p>