0

Still having problems understanding how to free the memory for a single linked list. I went over the presentation and put together this snippet of code:

void destroy(sllnode* head)
{
// *base case* if you've reached a null pointer, stop
if(head == NULL)
{
    return;
}

// *recusive case*
else
{
    // destroy the rest of the list
    return destroy(head->next);

    // Free the current node
    free(head);

    return;
}

}

I still get memory leaks with this so I know I'm not doing something right. Thanks in advance.

0

Look at this part of the code:

else
{
    return destroy(head->next);
    free(head);
    return;
}

The free(head); statement will never execute because the call to destroy() in the previous line has a return attached to it. Because of that return, the code will always recursively return to the prior calling code rather than execute the free.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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