【发布时间】:2017-04-19 00:47:51
【问题描述】:
在我附加的 C 程序中,我定义了一个名为 push() 的单独函数,用于在链表的前面添加一个节点。 push() 在堆上为node 分配内存,但我不能在这里释放内存,因为push() 所做的工作不会反映在调用者(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
}
【问题讨论】:
标签: c memory-management linked-list