我需要释放局部变量吗?

Thi*_* G. 9 c free pointers linked-list

我有以下内容struct:

typedef struct cell Cell;
struct cell {
    int value;
    int *nextcell;
};
Run Code Online (Sandbox Code Playgroud)

我有以下功能来释放链表:

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);
}
Run Code Online (Sandbox Code Playgroud)

Lee*_*eor 8

不,释放是针对动态分配的内存,指针只是指向那里的变量.你的循环释放了列表所占用的所有内存 - 此时没有任何东西可以释放并试图再次释放相同的内存(开始)会导致错误.在循环为NULL之后的thisCell那里甚至没有东西可以释放.

如果您指的是指针本身,则它们不会动态分配内存,当您定义它们时,它们每个都在堆栈上占用一个插槽,而保留该函数将释放该插槽.这里我们只讨论指针本身(它们指向的地址存储的位置),而不是它们可能持有的指向内存.