Search code examples
clinked-listmallocfree

How to free a linked list?


I have created a linked list in a function and throughout the rest of the program I am accessing the list using a pointer. Now how would I free this linked list at the end of my program? Do I plainly use free(CircuitData) or do I have to run through the list freeing each node? Writing this I'm thinking freeing each node is the obvious answer...

On a side note I'd also like to ask how to find out whether all memory allocated during a program is freed properly?

 ListNodeType *CircuitData;
 CircuitData = NULL;
 ReadFile(&CircuitData, &numEl, &numNodes);


void ReadFile(ListNodeType **CircuitData, int *numEl, int *numNodes){

    ListNodeType *newPtr, *tempPtr;
    newPtr = malloc(sizeof(ListNodeType));
    *CircuitData = newPtr;
    newPtr->nextPtr = NULL;

    //MORE CODE

Solution

  • For every malloc you will need a free otherwise you will leak memory. One possible way to analyze your program to see if you don't have memory leaks is to use Valgrind.