0

I have created the below function to free memory allocated by the create_family.

// Free `p` and all ancestors of `p`.
void free_family(person *p)
{
    // TODO: Handle base case
    if(p == NULL)
    {
        return;
    }
    // TODO: Free parents
    else if(p->parents[0] != NULL)
    {
        free_family(p->parents[0]);

    }
    
    else if(p->parents[1] != NULL)
    {
        free_family(p->parents[1]);
    }
    else{
        free(p);
    }
    // TODO: Free child
}

While it's longer and less concise than the provided answer. As far as I can tell it executes in the same way.

It checks if pointer p has values in parents[0] and parents[1]. If the value inside parents[x] aren't NULL then it recursively executes free_family.

Eventually freeing everything. What am I missing here?

1
  • If one of the conditional statements execute, the others will be omitted. Also no need to check whether each of the parents are NULL. your base case is supposed to do that
    – C--
    Apr 25 at 5:01
0

The various branches are mutually exclusive. Only one of them will execute the way you've written it. But you want to free both the parents and the person.

And why check for NULL here?

else if(p->parents[0] != NULL)
{
    free_family(p->parents[0]);

}

The parent will just be checked for NULL again once it is passed to free_family as a person.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .