0

consider the following structures:

struct intNode
{
    int num;
    intNode* pNext;
};

struct list
{
    intNode* first;
    intNode* last;
    int size;

};

suppose I allocated memory for the list. If I call free(lst) will it also free the memory allocated to the intNode first and last? and what about their own pNext? Intuitively I feel like I need to recursively free the nested memory blocks from the inside out.

Or Cyngiser
  • 1,027
  • 1
  • 12
  • 16
  • 1
    you `free()` for every `malloc()` since `malloc()` is not magic. –  Sep 22 '13 at 16:09
  • possible duplicate of [C - freeing structs](http://stackoverflow.com/questions/13590812/c-freeing-structs) –  Sep 22 '13 at 16:09
  • 1
    The proposed duplicate is dealing with the converse case, where allocating a structure does not require the release of anything else because the members are not pointers. – Jonathan Leffler Sep 22 '13 at 16:39

2 Answers2

2

You need to free them all individually, but usually for linked lists this is done iteratively, not recursively:

void DeleteList(struct intNode *pHead)
{
    struct intNode *pCur=pHead, *pDel=NULL;
    while(pCur != NULL)
    {
        pDel = pCur;
        pCur = pCur->pNext;
        free(pDel);
    }
}
Medinoc
  • 6,577
  • 20
  • 42
0

If you only frees memory of list element (when you have nodes), you cause a memory leak. In memory, the list looks like this:

 [list caption]...other data...[node]...other data...[node]...[last node]
  ^(It is not always first!)

So, nodes aren't one uninterrupted memory area and they are not in contact with the caption. In these elements you have only address of next node, therefore you must free them memory of each element separately. If you do it only with the caption, the nodes remain in the memory. Furthermore you'll lose the address of first node, thereby you'll lose all addresses of all elements! In this case, you will not be able to get to the nodes or free their memory.

In response to your question, yes, you should do more. Freeing "parent's" memory isn't enough. In general, you should use free as much times as you use malloc or calloc. In this case it is simple. I just need to get the address of the first node and sequentially purified memory. Do not forget to keep the address of the next node (in a variable) before removing recent.

nobody
  • 19,814
  • 17
  • 56
  • 77
Tacet
  • 1,411
  • 2
  • 17
  • 32