c - 如何从另一个函数释放一个函数动态分配的内存?

标签 c memory-management linked-list

在我附加的 C 程序中,我定义了一个名为 push() 的单独函数,用于将节点添加到链表的前面。 push() 为堆上的 node 分配内存,但我无法释放此处的内存,因为这样 push() 完成的工作将不会反射(reflect)在调用者中 (main())。那么如何从 main() 内部释放相关的堆分配内存呢?

感谢任何形式的帮助。提前致谢。

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

/* Prototypes */
void push(struct node **headRef, int data);

int main(void)
{
    struct node *head, *tail, *current;
    int i;

    head = NULL;

    // Deal with the head node here, and set the tail pointer
    push(&head, 1);
    tail = head;        // tail and head now point to the same thing

    // Do all the other nodes using TAIL
    for (i = 2; i < 6; i++)
    {
        push(&(tail->next), i);     // add node at tail->next
        tail = tail->next;          // advance tail to point to last node
    }

    current = head;
    while (current)
    {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");

    return 0;
}

/*
 Takes a list and a data value.
 Creates a new link with the given data and pushes
 it onto the front of the list.
 The list is not passed in by its head pointer.
 Instead the list is passed in as a "reference" pointer
 to the head pointer -- this allows us
 to modify the caller's memory.
*/
void push(struct node **headRef, int data)
{
    struct node *newNode = malloc(sizeof(struct node));
    newNode->data = data;
    newNode->next = *headRef;   // The '*' to dereference back to the real head
    *headRef = newNode;         // ditto
}

最佳答案

您可以像这样释放main中分配的空间 -

struct node * tmp;
while(head){
    tmp = head;
    head = head->next; //this is to avoid loosing reference to next memory location
    free(tmp); 
}

由于您在 push 中传递了变量的地址,因此这是可能的。

关于c - 如何从另一个函数释放一个函数动态分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40960483/

相关文章:

c - 在结构C中锁定pthread_mutex_t

c - C 中的线程加工错误?

java - 组播发送性能

c++ - 在这种情况下如何使用 auto_ptr

c++ - C 与 C++ 在内存分配方面的性能

ios - 我们必须在 -init 中将所有属性设置为 nil 还是自动发生?

java - 循环分配/链接的 GWT 垃圾收集

c - 程序不会在第二次 scanf() 时读取

java - 将线性链表打印到表中

java - 如何在 Java 中的 Stack/Queue 类中实现通用 LinkedList