简体   繁体   English

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

[英]How can I free memory that has been dynamically allocated by one function from another function?

In the C program I've attached, I've defined a separate function called push() to add a node to the front of a linked list.在我附加的 C 程序中,我定义了一个名为push()的单独函数,用于将节点添加到链表的前面。 push() allocates memory for a node on the heap, but I cannot free the memory here because then the work done by push() will not be reflected in the caller ( main() ). push()为堆上的一个node分配内存,但我不能在这里释放内存,因为这样push()完成的工作将不会反映在调用者 ( main() ) 中。 So how can I free the concerned heap-allocated memory from inside main() ?那么如何从main()内部释放相关的堆分配内存?

Any sort of help is appreciated.任何形式的帮助表示赞赏。 Thanks in advance.提前致谢。

#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
}

You can free the allocated space in main like this -您可以像这样在main释放分配的空间 -

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

Since you pass address of variable in push , therefore, this could be possible.由于您在push传递变量的地址,因此,这是可能的。

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

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