简体   繁体   中英

why will “malloc” change unrelated pointer in my case?

I'm trying to implement a binary search tree (BST) in C. I have tried to add several elements to the BST, but when I add the third one, the code doesn't work. I debug it in gdb and find that when it executes malloc for the new node, the second node's parent changes from a correct address value to 0x13 .

Since I feel that there is no relation between the new node's memory allocation and the old node's parent, I have no idea why does this happens…

Here is my InsertBST function:

int InsertBST(Bst *p, int val)
{
    PNode pnode = (PNode)malloc(sizeof(PNode));
    if (pnode != NULL)
    {
        pnode->data = val;
        pnode->lc = NULL;
        pnode->rc = NULL;
        if (p->root == NULL)
        {
            pnode->parent = NULL;
            p->root = pnode;
            p->size++;
            return 1;
        }
        else
        {
            PNode tem = FindVal(p->root, val);
            if (tem != NULL)
            {
                printf("Sorry, the value %d has appeared!\n", val);
                return 0;
            }
            else
            {
                tem = p->root;
                while (tem->lc != NULL && tem->rc != NULL)
                {
                    if (tem->data > val)
                        tem = tem->lc;
                    else
                        tem = tem->rc;
                }
                pnode->parent = tem;
                if (tem->data > val)
                {
                    tem->lc = pnode;
                }
                else
                {
                    tem->rc = pnode;
                }
                p->size++;
            }
            return 1;
        }
    }
    else
    {
        printf("Allocate memory failed!\n");
        return 0;
    }
}

p is pointer to a structure like this:

typedef struct BST
{
    PNode root;
    int size;
}Bst;

and PNode is pointer to a structure like this:

typedef struct NODE
{
    int data;
    PNode lc;
    PNode rc;
    PNode parent;
}Node;
malloc(sizeof(PNode))

will allocate the memory needed for a pointer, not for the node structure behind it.

Try

malloc(sizeof(*PNode))

or

malloc(sizeof(Node))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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