phip1611
phip1611

Reputation: 6170

Segmentation fault and pointer to non existing struct is not null

I have the following struct:

typedef struct treeNode *tree;
typedef struct treeNode {
  int key; 
  tree left, right;
} treeNode;

with this tree:

my tree

problem: mytree->left->left->left is NOT NULL. But why?! How Can I check if I reached the end of a branch?

  tree mytree = (tree)malloc(sizeof(treeNode));
  mytree->key = 17;
  mytree->left = (tree)malloc(sizeof(treeNode));
  mytree->left->key = 5;
  mytree->left->left = (tree)malloc(sizeof(treeNode));
  mytree->left->right = (tree)malloc(sizeof(treeNode));
  mytree->left->left->key = 20;
  mytree->left->right->key = 2;
  mytree->right = (tree)malloc(sizeof(treeNode));
  mytree->right->key = 1;
  mytree->right->left = (tree)malloc(sizeof(treeNode));
  mytree->right->right = (tree)malloc(sizeof(treeNode));
  mytree->right->left->key = 6;
  mytree->right->right->key = 3;

Upvotes: 2

Views: 210

Answers (1)

Heath Hunnicutt
Heath Hunnicutt

Reputation: 19467

When you allocate a treeNode, do you initialize the pointers to NULL? C doesn't magically initialize dynamically allocated memory.

You added your initialization code. malloc() does not initialize the contents of the memory to zero. There's nothing in your code that would set the left and right pointers to NULL. That's why they aren't NULL. You can either initialize them by hand (best for you), or use calloc() instead of malloc(). calloc() initializes the allocated memory to zero.

Upvotes: 5

Related Questions