从函数返回后释放内存

  • 本文关键字:释放 内存 返回 函数 c
  • 更新时间 :
  • 英文 :

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//defined a data structure "node" which stores an int and a pointer to a node
typedef struct node
{
int number;
struct node *next;
}
node;
//defining functions
node* create(int number);
node* insert(node *new_linked_list, int number);
void print(node *new_linked_list);
void delete_list(node *new_linked_list);
int main(void)
{
//create new linked list with function
node *new_linked_list = NULL;

//get input to update list
for (int i = 0; i < 10; i++)
{
int temp;
if (i == 0)
{
scanf(" %i", &temp);
printf("n");
new_linked_list = create(temp);
continue;
}

//will insert new nodes in the linked lists
scanf(" %i", &temp);
printf("n");
new_linked_list = insert(new_linked_list, temp);
}

//prints node number values out
print(new_linked_list);

//delete/free list
delete_list(new_linked_list);



}
//function will return a pointer to the first node in the list
node* create(int number)
{
node *firstnode = malloc(sizeof(node));
firstnode -> number = number;
firstnode -> next = NULL;

return firstnode;
}
//function that will update the linked list and return a pointer to the new head of the linked list
node* insert(node *new_linked_list, int number)
{
node* new_node = malloc(sizeof(node));
if (new_node == NULL)
{
return new_linked_list;
}

//new node will point to the old first node and updates new_nodes number
new_node -> number = number;
new_node -> next = new_linked_list;

//returns a pointer to the new first node
return new_node;
}
void print(node *new_linked_list)
{
//temporary node for reversal
node *trav = new_linked_list;

for (int i = 0; i < 10; i++)
{
printf("%i   ",trav -> number);
trav =  trav -> next;

if (i == 9)
{
printf("n");
}
}
}
void delete_list(node *new_linked_list)
{
//base case: at null pointer
if (new_linked_list -> next == NULL)
{
//frees memory previously allocated to a pointer
free(new_linked_list);
return;
}

//else delete the rest of the list
else
{
delete_list(new_linked_list -> next);
}

}

嗨,我正在试验一个链表,遇到了一个问题。我的程序泄漏内存,因为我没有释放"新节点"。然而,我对如何释放它感到困惑,因为它正在返回到main中使用。我该如何释放"新节点"呢?同时仍然能够在主函数中使用它。事先感谢您的帮助。

这个问题似乎与'delete_list'的递归行为有关

可以这样实现:

void delete_list(node *new_linked_list)
{
node *next;
while(new_linked_list != NULL)
{
next = new_linked_list->next;
free(new_linked_list);
new_linked_list = next;
}
}

最新更新