initializing a tree in c

431 Views Asked by At

im trying to initialize a tree data structure but everytime i invoke initTree(); my program terminates without any output my initTree():

Tree* initTree(){
Tree* tree = (Tree*) malloc(sizeof(Tree));
tree->root = NULL;
tree->root->left = NULL;
tree->root->right = NULL;
tree->height = 0;
return tree;
}

however when i remove the 2 lines tree->root->left = NULL; and tree->root->right = NULL; my program works fine , is there any explanation??

1

There are 1 best solutions below

0
On

The function invokes undefined behavior because there is used a null pointer

tree->root = NULL;
^^^^^^^^^^^^^^^^^^  

to access memory in these statements

tree->root->left = NULL;
^^^^^^^^^^
tree->root->right = NULL;
^^^^^^^^^^

That is the pointer tree->root does not point to a valid object. Thus the two statements above do not make a sense and should be removed.

You may not use a null pointer to access memory.