Home:ALL Converter>How to free allocated memory in a binary tree in C

How to free allocated memory in a binary tree in C

Ask Time:2015-02-25T03:59:14         Author:Hotsaucejalapeno

Json Formatter

I am having trouble with a function in my C program. The purpose of the program is to:

  • Read integers from a binary file into an array
  • Sort these numbers using a binary tree
  • Do some other stuff
  • Free all memory that you allocated using malloc();

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).

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;

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.

/*
 * Frees the memory allocated for
 * each node
 */
void freeNode(NodeP p)
{
    if(p == NULL) return;
    freeNode(p->L);
    freeNode(p->R);
    free(p);
}

/*
 * Frees the memory allocated
 * for the tree
 */
TreeP freeTree(TreeP tree)
{
    if(tree->root == NULL)
        free(tree);
    else
    {
        freeNode(tree->root);
        free(tree);
    }

    return NULL;
}

When I run this program, my debugger is giving me this error.

EXC_BAD_ACCESS (code=EXC_I386_GPFLT)

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!

EDIT:

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!

https://copy.com/902v0bMv8DtIMUrc

Author:Hotsaucejalapeno,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/28705133/how-to-free-allocated-memory-in-a-binary-tree-in-c
yy