Patrick Kochan
Patrick Kochan

Reputation: 5

Free behavior with linked lists

When removing an element from a linked list by just moving the pointer. Will free get rid of the memory after the element in the linked list is no longer connected to the list?

Upvotes: 0

Views: 54

Answers (3)

Mike Housky
Mike Housky

Reputation: 4069

I assume that "Will free get rid of the memory..." is referring to the free() function. Yes, the free() function will free all of the memory allocated by a single malloc(), calloc() or realloc() call.

Make sure you've completely unlinked the entry before calling free(). Any use of the memory (read or write) after calling free() is undefined behavior.

Upvotes: 0

pm100
pm100

Reputation: 50190

free will release whatever you point it at. Nothing happens by magic. YOu must call free on the unlinked element

What you hoping for (automatic release of memory when no longer in use) is provided by either reference counted pointers (like shared_ptr in c++) or garbage collection (in C#, Java, javascript,...)

Upvotes: 2

jmann
jmann

Reputation: 36

Not unless you explicitly free it. free takes in a pointer and marks that memory as ready for future use.

You have to free the memory used by that linked list element, then move your pointers around. If you lose all pointers to that element before you free it, then you can't free it, thus creating a memory leak.

Upvotes: 1

Related Questions