I have some problem with this code. Notice the comments. Why that?
struct node
{
struct node *left;
struct node *right;
int value;
};
static struct node root2;
int main()
{
struct node *root = (struct node *) malloc(sizeof(struct node));
assert(root->left == NULL); /* not failed. Why? */
assert(root->right == NULL); /* not failed. Why? */
assert(root2.left == NULL); /* not failed. Why? */
assert(root2.right == NULL); /* not failed. Why? */
struct node root1;
assert(root1.left == NULL); /* this failed. Why? */
assert(root1.right == NULL); /* this failed. Why? */
free(root);
return 0;
}
With root1, you’ve declared a local instance of a node, and it will be on the stack. You don’t initialise it, so it will contain garbage.
With root2, you’ve declared a global instance. The default startup code will clear the memory that globals occupy.
With root, it will exist on the heap, and will contain garbage. It is pure luck whether the memory occupied contains 0 or not. If you use calloc instead of malloc, it will clear the memory for you.