14

I have the following struct:

typedef struct cell Cell;
struct cell {
    int value;
    int *nextcell;
};

And I have the following function to free a linked list:

void freelist(Cell *beginning)
{
    Cell *thisCell = beginning;
    Cell *NextCell = beginning->nextcell;

   while (thisCell != NULL)
   {
        NextCell = thisCell->nextcell;
        free(thisCell);
        thisCell = NextCell;
   }

   /* Here comes my question. Do I need to free the following variables? */
   free(beginnig);
   free(thisCell);
   free(NextCell);
}
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
Thi G.
  • 1,578
  • 5
  • 16
  • 27

2 Answers2

14

No, freeing is intended for the dynamically allocated memory, a pointer is just a variable that points there. Your loop frees all the memory the list took - at that point there's nothing to free and trying to free the same memory again (beginning) would result in an error. thisCell after the loop is NULL there there's not even something to free there.

If you meant the pointers themselves, they did not allocate memory dynamically, when you defined them they each took a slot on the stack, and leaving the function would release that slot. Here we're only talking about the pointers themselves (the place where the address they point to is stored), not the pointed memory they might hold.

Leeor
  • 19,260
  • 5
  • 56
  • 87
  • Best way to check if this is true is to try apply free() on a variable stored on the stack and see what happens. :) – rbaleksandar Nov 19 '13 at 16:08
2

You free memory that you allocate no matter where the pointer is stored - in a local variable, in a global / static variable, or in a pointer that is allocated on the free store itself.

Your function frees several pointers multiple times: you do not need any of the three calls to free at the bottom of your function (although the second call is harmless, because it passes NULL to free, which is always OK).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523