Home > Back-end >  Pointer value gets randomly reassigned in a tree problem
Pointer value gets randomly reassigned in a tree problem

Time:11-23

In a normal tree problem, let's say there's a function fun.

void fun(Node **root)
{
    printf("%p\n", *root); // here it prints a non nil memory address
    if (*root == NULL || (*root)->left == NULL)
        return;
    Node *p = (*root)->left;

    p->parent = (*root)->parent;
    printf("%p", *root); // here it prints root as nil
    //...
}

In which case could this happen, considering that tree contains only 3 2 1, with all of them being added to the left.

Here's the minimal reproducible code sample:

#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
    int data;
    struct Node *left, *right, *parent;

} Node;

void fun(Node **root)
{
    printf("%p\n", *root); // here it prints a non nil memory address
    if (*root == NULL || (*root)->left == NULL)
        return;
    Node *p = (*root)->left;

    p->parent = (*root)->parent;
    printf("%p", *root); // here it prints root as nil
    //...
}
void fun1(Node **root)
{
    if (*root && (*root)->parent && (*root)->parent->parent)
    {
        fun(&((*root)->parent->parent));
    }
}
void add(Node **root, Node *parent, int data)
{
    if (*root == NULL)
    {
        *root = (Node *)malloc(sizeof(Node));
        (*root)->data = data;
        (*root)->left = (*root)->right = NULL;
        (*root)->parent = parent;
        fun1(root);
        return;
    }

    if (data < (*root)->data)
        add(&((*root)->left), *root, data);
    else if (data > (*root)->data)
        add(&((*root)->right), *root, data);
}

int main()
{
    Node *root = NULL;
    add(&root, NULL, 3);
    add(&root, NULL, 2);
    add(&root, NULL, 1);
    return 0;
}

CodePudding user response:

When fun1 calls fun, the root parameter of fun is pointing to the parent member of the node with data 2.

That parent member points to the node with data 3. So *root points to the node with data 3. And (*root)->parent is a null pointer.

In fun, Node *p = (*root)->left sets p to point to the left child of (*root), which is the node with data 2.

Then p->parent = (*root)->parent; sets p->parent to a null pointer. Since p points to the node with data 2, p->parent is the parent member of the node with data 2, and that is what root points to.

  • Related