I am creating a binary tree from a bitstring in c. ie 1100100 creates a tree:
1
/ \
1 1
I decided to use a recursive function to build this tree however i keep getting the error
Debug assertion failed…
Expression : CrtIsValidHeapPointer(pUserData)
here is a fragment of my code
typedef
struct Node {
char key;
struct Node *left;
struct Node *right;
} Node;
char string[1000];
int i = 0;
void insertRecursivePreorder(Node **node)
{
Node* parent = *node;
if(string[i] == '0')
{
parent = NULL;
i++;
}
else
{
Node *newn = (Node*)malloc(sizeof(Node));
newn->key = string[i];
parent = newn;
i++;
insertRecursivePreorder(&newn->left); //errors occur here
insertRecursivePreorder(&newn->right); //errors occur here
free(newn);
free(parent);
}
}
int main(void)
{
void printTree(Node* node);
Node* root = NULL;
scanf("%s", string);
insertRecursivePreorder(&root);
//... do other junk
}
i was wondering why this error comes about and what i can do to fix it.
The immediate problem is likely to be calling
freeon a pointer twice. IninsertRecursivePreorder, you setparenttonewn, and then callfreeon both. As an example of this, the following program fails (but works if you comment out one of thefree(..)s):However, there are several problems with your logic here. You should only call
freewhen you have completely finished with the pointer, so if you are using your tree later you can’t free it as you construct it. You should create a second function,recursiveDestroyTree, that goes through and callsfreeon the tree (from the bottom up!).And, you probably want
*node = newnrather thanparent = newn, since the latter is the only one that actually modifiesnode.(You could also change your function to return a
Node *pointer, and then just go:and
instead of trying to keep track of pointers to pointers etc.)
(Furthermore, on a stylistic point, using global variables is often bad practice, so you could have your
insertRecursivePreordertakeint iandchar * stringparameters and use them instead of global variables.)