繁体   English   中英

如何从 C 中的调用者 function 释放由局部变量分配的 memory?

[英]How to free memory allocated by a local variable from the caller function in C?

我有一个像下面这样的 function,我想释放调用者 function 中的temp1变量分配的 memory。

// Code to insert element at Nth position
void Insertion (int num, Node **head)
{
    // I can't free this variable in this function because 
    // it will be used in future to navigate through the list. 
    // I would like to avoid global variables as well.
    Node *temp1 = (Node*)malloc(sizeof(Node)); 
    temp1->data = data;
    temp1->next = NULL;

    Node *temp2 = *head;
    for (int i = 0; i < position - 2; i++)
    {
        temp2=temp2->next;
    }
    temp1->next = temp2->next;
    temp2->next = temp1;

    return 0;
}

调用方 function 如下所示

int main(void)
{
    Node *head = NULL;

    Insertion (30, 1, &head);
    .....
    .....

    return 0;
}

有谁知道我在这里有什么选择?

  1. 我是否应该将Insertion的返回类型从void更改为void * ,然后释放 function? 我有一种强烈的感觉,我在这里做了一些无效的事情。
  2. 我应该将 temp1 作为参数传递吗? (这会使事情过于复杂,所以我想避免这种方法)

这是一种释放链表的方法。

struct Node {
    void *data;
    struct Node *next;
};

void free_list(struct Node *head)
{
    if(head->next)
        free_list(head->next);
    if(head->data)
        free(head->data);
    free(head);
}

暂无
暂无

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

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