C – 如何释放动态分配的内存?

看看这段代码,它是链表的一部分。

int main() { List* head1 = NULL; insertFront(&head1, 1); insertFront(&head1, 2); print(head1); free(head1); return 0; } 

另一个function是:

 void insertFront(List** head, int value) { List* node = (List*)malloc(sizeof(List)); node->data = value; node->next = NULL; node->next = *head; *head = node; //free(node); essentially I am not freeing node } 

我的问题是:

  1. 我的代码是否会导致内存泄漏问题?

  2. 我是否需要为节点(在函数内部)释放已分配的内存(动态)?

  3. 如果我释放head1,那么为节点分配的内存是否也会被释放? 如果是,那怎么样?

您有内存泄漏,因为您只释放列表中的第一个节点。 你不想在insertNode函数中free ,否则你会立即丢弃你刚刚分配的内存。

在程序结束时,您需要遍历列表并free每个元素。

 while (head1) { List *temp = head1; head1 = head1->next; free(temp); }