user4120120
user4120120

Reputation:

Building a BST(non recursive/non iterative) in C

I am trying to add nodes to a BST in C and print it out. This is a very simple and direct implementation, I am getting a memory leak. I have been stuck on this for hours, please help me see whats wrong. My code is:

struct bstnode {
int item;
struct bstnode *left;
struct bstnode *right;
};

void destroy_tree(struct bstnode *t) {
if (NULL == t) {return;}
destroy_tree(t->left);
destroy_tree(t->right);
free(t);
}
void inorder_print(struct bstnode *t) {
if (NULL == t) {return;}
inorder_print(t->left);
printf("  %d", t->item);
inorder_print(t->right);
}

 int main(void) {

 struct bstnode *myt = malloc(sizeof(struct bstnode));
 struct bstnode *l = myt->left ; 
 struct bstnode *r = myt->right;
 l->item = 20;
 l->left = NULL;
 l->right = NULL;
 r->item = 30;
 r->left = NULL;
 r->right = NULL;
 myt->item = 25;
 inorder_print(myt);
 printf("\n");
 destroy_tree(myt);}

I suspect there is an error in my pointer assignment please explain me what mistake I made.

Thanks in advance!

Upvotes: 0

Views: 83

Answers (1)

gia
gia

Reputation: 757

Pointers initialize to an unknown value, whatever was in that area of memory during their creation, so assume they are "dirty", paranoid programmers "clean" them up before working, but is not necessary if you understand working with pointers. One way to clean is to create a constructor for your struct that initializes its internal pointers to NULL. Now you know they are NULL. Research constructors in c++.

Now do add the constructor, (you use malloc, so your constructor won't be called automatically, do call it manually, you could change it to an Init() function to prevent semantics headaches). Call Init() as soon as you malloc. Now check your code again, what's wrong with it? is the error more clear?

You only construct myt bstnode on the first line, L then becomes myt->left (null/undefined), and so does R

then you access a content of L, which is null so crash.

Upvotes: 1

Related Questions