Binary Tree in c -> crashes at depth of more than 7

96 Views Asked by At
  1. I have made a simple binary tree structure in c.
  2. In main(), a tree is CREATED, PRINTED and DELETED (to test if everything is in order).
  3. It works fine to the depth of 7 nodes but if i set the depth to 8 or more it crashes.
  4. I've tried many things but the result is always the same, I seem to be missing some basic concept.
  5. All comments appreciated.

    #include<stdio.h>
    #include<stdlib.h>
    
    typedef struct tree tree;
    
    struct tree{
        int depth;
        int data;
        tree *up;
        tree *left;
        tree *right;
    };
    
    void printTree(tree *node){
        if(node){
            for(int i = 0; i < node->depth; ++i) printf("\t");
            printf("%d: ", node->depth);
            printf("%d\n", node->data);
            printTree(node->left);
            printTree(node->right);
        }
    }
    
    void fillTree0(tree *node){
        if(node->depth < 8){ //depth of 8
            //deklaration
            node->left = new tree;
            node->right = new tree;
            //set up
            node->left->up = node;
            node->right->up = node;
            //set depth
            node->left->depth = node->depth +1;
            node->right->depth = node->depth +1;
            //set data 0
            node->left->data = 0;
            node->right->data = 0;
            //recursion
            fillTree0(node->left);
            fillTree0(node->right);
        }
    }
    
    void freeTree(tree *node){
    
        if(node->left) freeTree(node->left);
        if(node->right) freeTree(node->right);
    
        delete(node->left); node->left = NULL;
        delete(node->right); node->right = NULL;
    
    }
    
    
    int main(void){
    
        tree *root;
        root = new tree;
    
        root->depth = 0;
        root->data = 0;
        fillTree0(root);
    
        printTree(root);
    
        freeTree(root);
    
        return 0;
    
    }
    
2

There are 2 best solutions below

0
On

Short answer: Add a constructor to tree. tree(){ up=left=right=0; }

The pointers are not initialized to be 0 (null, nullptr) by default.

The problem does not come form the magic 7 or 8 as you described.

0
On

You have to initialize your nodes pointers left and right to NULL:

    node->left = new tree;
    node->left->left = NULL ;
    node->left->right = NULL ;

    node->right = new tree;
    node->right->left = NULL ;
    node->right->right = NULL ;

Because your print function:

void printTree(tree *node){
    if(node){ //<-- this is equal to if( node != NULL)

relies on invalid pointers left and right to be NULL, if they are not you will access unallocated memory and cause segfault.