简体   繁体   中英

possible memory leak using pointers with malloc() and free(), and confusion with pointer notation

So I'm relatively new to C, and I was trying to write code for a singly linked list.

This is what I wrote for deleting a node from the beginning of the list.

int delete(struct node **head)
{
    int x = -1;
    if(*head != NULL) {
        struct node *old = *head;
        (*head) = (*head)->next;
        x = old->data;
        free(old);
    }
    return x;
}

and I'm confused at the free() function. Am I freeing the space allocated to the pointer old , or am I freeing it to the address at which old points? Maybe the correct way of doing it would be free(*old) ? Will this code cause a memory leak?

Also, if this frees the memory allocated to old, what would be the effect of free(&old) , in that case?

From what you show the memory management seems OK and does not seem to leak memory.

Am I freeing the space allocated to the pointer old

Yes, the code deallocates, frees to memory old points to, which is commonly referred to as the memory being allocated to a pointer .


free(*old) wouldn't work, as it wouldn't compile, because you tried to pass a struct into where a pointer is expected.

free(&old) wouldn't work, as it would provoke undefined behaviour, because the code tried to free memory being allocated on the stack, that is the memory for the pointer variable old itself.

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