为什么动态分配释放“两次"?单链表的head_node(first_node)何时初始化? [英] Why does dynamic allocation release "twice" when head_node(first_node) of the singly linked list initialize?

查看:65
本文介绍了为什么动态分配释放“两次"?单链表的head_node(first_node)何时初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道两次动态分配释放的原因.
我认为,初始化headnode时只使用一次 free function .

I want to know the reason for twice of dynamic allocation release.
I think, use free function just one time when initializing of headnode.

这里是代码!!:)

int freeList(headNode* h){
    listNode* p = h->first;
    listNode* prev = NULL;   
    
    while(p != NULL) {      
        prev = p;           
        p = p->link;         
        free(prev);    /* Here is a problem
                        What is a few errors with just coding free(prev)? */    
    }
    free(h);  /* Here is a problem */  
    return 0;
}

推荐答案

free(prev) free(h)是关于不同的数据结构:

free(prev) and free(h) are about different data structures:

  • free(prev)正在释放 listNode 实例的内存
  • free(h)正在释放 headNode 实例的内存.
  • free(prev) is freeing the memory of a listNode instance
  • free(h) is freeing the memory of a headNode instance.

headNode 有点混乱,因为我认为结构实际上并不代表列表中的 first 节点,而是容器".为列表.它具有一个 first 指针,该指针可以为 NULL (如果表示的链表为空),也可以是指向第一个节点的指针.无论哪种方式, headNode 实例都与它可能引用的第一个节点的实例有所不同(仅当表示的链表不为空时).

headNode is a bit of a confusing name, as I assume that structure does not actually represent the first node in a list, but is the "container" for the list. It has a first pointer which may be NULL (in case the represented linked list is empty), or may be a pointer to the first node. Either way, a headNode instance is something different than the instance of the first node it might refer to (only when the represented linked list is not empty).

因此,您的循环释放了列表中所有节点的内存,而对 free 的最终调用是关于 headNode 实例的,而不是节点链表的,但是是链表的容器.

So your loop frees the memory of all the nodes in the list, while the final call to free is about the headNode instance, which is not a node of the linked list, but is the container for the linked list.

这篇关于为什么动态分配释放“两次"?单链表的head_node(first_node)何时初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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