C-如何释放动态分配的内存? [英] C - How can I free dynamically allocated memory?

查看:174
本文介绍了C-如何释放动态分配的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这段代码,它是链接列表的一部分.

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;
}

另一个功能是:

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. 我的代码会导致内存泄漏问题吗?

  1. Is my code going to cause memory leak problem?

我是否需要(动态地)释放节点(哪个在函数内)分配的内存?

Should I need to free the allocated memory (dynamically) for node (Which is inside a function)?

如果我释放head1,分配给节点的内存也将被释放吗?如果是,那么如何?

If I free head1, will the memory allocated for node also be freed? If yes, then how?

推荐答案

由于仅释放列表中的第一个节点,因此内存泄漏.您不想在insertNode函数中使用free,否则您将立即丢弃刚刚分配的内存.

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.

在程序结尾,您需要遍历列表,并free每个元素.

At the end of your program, you need to traverse the list and free each element.

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

这篇关于C-如何释放动态分配的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆