简体   繁体   English

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

[英]C - How can I free dynamically allocated memory?

Have a look at this piece of codes, it's part of a linked list. 看一下这段代码,它是链表的一部分。

int main()

{
    List* head1 = NULL;

    insertFront(&head1, 1);
    insertFront(&head1, 2);

    print(head1);

    free(head1);

    return 0;
}

another function is: 另一个功能是:

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
}

My questions are: 我的问题是:

  1. Is my code going to cause memory leak problem? 我的代码会导致内存泄漏问题吗?

  2. Should I need to free the allocated memory (dynamically) for node (Which is inside a function)? 我是否需要(动态地)释放节点(哪个在函数内部)分配的内存?

  3. If I free head1, will the memory allocated for node also be freed? 如果我释放head1,分配给节点的内存也将被释放吗? If yes, then how? 如果是,那怎么办?

You have a memory leak because you are only freeing the first node in the list. 因为仅释放列表中的第一个节点,所以内存泄漏。 You don't want to free in the insertNode function otherwise you're immediately throwing away memory you just allocated. 你不希望freeinsertNode功能,否则你会立即扔掉你刚才分配的内存。

At the end of your program, you need to traverse the list and free each element. 在程序结束时,您需要遍历列表并free每个元素。

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

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

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