2016-12-04 149 views
-1

在我附加的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 
} 

回答

0

您可以在main這樣釋放分配的空間 -

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

既然你在push傳遞變量的地址,因此,這是可能的。