[英]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;
}
有谁知道我在这里有什么选择?
Insertion
的返回类型从void
更改为void *
,然后释放 function? 我有一种强烈的感觉,我在这里做了一些无效的事情。这是一种释放链表的方法。
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.