Search code examples
cfunctionfree

C Programming free() Function Error


So here's a beginner question about free() function in C Programming, when I try to free the deallocate the memory in the end using free() function I keep getting double free or corruption error or the loop won't end, I had the same issue with the other similiar function I wrote in the same program. When did I do wrong?

int addnode(struct node *add, struct node *p,int dep)
{
    int count=0;
    dep=1;
    struct node *roo=(struct node*)malloc(sizeof(struct node*));
    roo=p;
    while(roo){
        if(add->data >roo->data&&roo->right!=NULL)
        {
            roo=roo->right;
            dep++;
        }
        if(add->data <roo->data&&roo->left!=NULL)
        {
            roo=roo->left;
            dep++;
        }
        if(add->data >roo->data&&roo->right==NULL)
        {
            roo->right=add;
            dep++;
            break;
        }
        if(add->data <roo->data&&roo->left==NULL)
        {
            roo->left=add;
            dep++;
            break;
        }
        free(roo);
    }
    return dep;
}

Solution

  • On one line you allocate the memory and assign to roo, and on next line you immediately assign it another value:

    struct node *roo=(struct node*)malloc(sizeof(struct node*));
    roo=p;
    

    The variable is reassigned several times later again. Therefore at the end it tries to free memory completely different than was allocated.

    The algorithm seems to be quite unclear, I suggest properly naming the variables and specifying purpose of input and output. So far it seems that the node to be added is already allocated when the function is called so there shouldn't be any reason for any additional allocation within this function.