gpt4 book ai didi

c - 如何从 C 中的调用函数中释放局部变量分配的内存?

转载 作者:行者123 更新时间:2023-11-30 20:29:15 25 4
gpt4 key购买 nike

我有一个如下所示的函数,我想释放调用函数中的 temp1 变量分配的内存。

// 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;
}

调用函数如下所示

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

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

return 0;
}

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

  1. 我是否应该将 Insertion 的返回类型从 void 更改为 void *,然后释放该函数?我有一种强烈的感觉,我在这里做了一些无效的事情。
  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);
}

关于c - 如何从 C 中的调用函数中释放局部变量分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58583350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com