简体   繁体   English

分段错误和指向不存在的结构的指针不为null

[英]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: 用这棵树:

我的树

problem: mytree->left->left->left is NOT NULL. 问题:mytree-> left-> left-> left不是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;

When you allocate a treeNode, do you initialize the pointers to NULL? 分配treeNode时,是否将指针初始化为NULL? C doesn't magically initialize dynamically allocated memory. C不会神奇地初始化动态分配的内存。

You added your initialization code. 您添加了初始化代码。 malloc() does not initialize the contents of the memory to zero. malloc()不会将内存的内容初始化为零。 There's nothing in your code that would set the left and right pointers to NULL . 有没有在你的代码,将设定的leftright指针NULL That's why they aren't NULL . 这就是为什么它们不是NULL的原因。 You can either initialize them by hand (best for you), or use calloc() instead of malloc() . 您可以手动初始化它们(最适合您),也可以使用calloc()代替malloc() calloc() initializes the allocated memory to zero. calloc()将分配的内存初始化为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM