简体   繁体   English

我需要释放局部变量吗?

[英]Do I need to free local variables?

I have the following struct : 我有以下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);
}

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. 在循环为NULL之后的thisCell那里甚至没有东西可以释放。

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. 这里我们只讨论指针本身(它们指向的地址存储的位置),而不是它们可能持有的指向内存。

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). 你的函数多次释放几个指针:你不需要在函数底部释放三个调用中的任何一个(尽管第二个调用是无害的,因为它将NULL传递给free,这总是正常的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM