Actually I just wrote a small program to test the code. My program has one struct allocated in memory, key_value is 5, and I insert a second struct, key_value 7, therefore inserted to the right.
My code is not art, so please bear with me:
Code:
/*
============================================================================
Name : BTree.c
Author : Me
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
//Classic BTree node \ leaf
struct node{
int key_value;
struct node *left;
struct node *right;
};
void insert(int key, struct node **ptr2ptr);
void destroy_tree( struct node *leaf);
int main(void) {
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
struct node *root;
struct node **ptr2ptr;
root = (struct node *)malloc(sizeof( struct node ));
root->key_value = 5;
root->left = 0;
root->right = 0;
*ptr2ptr = root;
insert(7, ptr2ptr);
destroy_tree (root);
return EXIT_SUCCESS;
}
void insert(int key, struct node **leaf){
if( (*leaf) == 0 ){
printf("\nLeaf doesn't exist yet. Will create leaf with key %d", key);
*leaf = (struct node *)malloc(sizeof(struct node));
(*leaf)->key_value = key;
(*leaf)->left = 0;
(*leaf)->right = 0;
}
else if( key < (*leaf)->key_value ){
printf("\nKey value is smaller. Will create leaf to the left");
insert( key, &(*leaf)->right);
}
else{
printf("\nKey value is greater or equal. Will create leaf to the right");
insert( key, &(*leaf)->left);
}
}
void destroy_tree( struct node *leaf){
if(leaf != 0){
destroy_tree(leaf->left);
destroy_tree(leaf->right);
printf("\nAbout to destroy leaf with key %d", leaf->key_value);
free(leaf);
}
else{
printf("\nLeaf does not exist.");
}
}
The output is as follows:
!!!Hello World!!!
Key value is greater or equal. Will create leaf to the right
Leaf doesn't exist yet. Will create leaf with key 7
Leaf does not exist.
Leaf does not exist.
About to destroy leaf with key 7
Leaf does not exist.
About to destroy leaf with key 5
If I make my code where the new struct or node is created the same as in the tutorial:
Code:
void insert(int key, struct node **leaf){
if( (*leaf) == 0 ){
printf("\nLeaf doesn't exist yet. Will create leaf with key %d", key);
*leaf = (struct node *)malloc(sizeof(struct node));
(*leaf)->left->key_value = key;
(*leaf)->left->left = 0;
(*leaf)->left->right = 0;
}
...
the output is as follows:
!!!Hello World!!!
Key value is greater or equal. Will create leaf to the right
Leaf doesn't exist yet. Will create leaf with key 7
Leaf does not exist.
Leaf does not exist.
About to destroy leaf with key 7
Leaf does not exist.
About to destroy leaf with key 5898436
Leaf does not exist.
About to destroy leaf with key 5
As you can see, it is freeing up some memory which it shouldn't be.
I would recommend that the code in the tutorial for BTree section for the insert function be corrected.
Best regards,
Daniel