作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个如下所示的函数,我想释放调用函数中的 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;
}
有谁知道我在这里有什么选择?
Insertion
的返回类型从 void
更改为 void *
,然后释放该函数?我有一种强烈的感觉,我在这里做了一些无效的事情。 最佳答案
这是一种释放链接列表的方法。
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/
我是一名优秀的程序员,十分优秀!