在C结构使用免费 [英] Using free on a C struct

查看:104
本文介绍了在C结构使用免费的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的链表节点如下:

I have a simple Linked List node as follows

typedef struct node {
    void *data;
    struct ListElement *next;           
} node;

另外我有一个节点,创建和删除功能如下:

Also I have a node create and delete function as follows:

void createNode(void *data){
    node *n = malloc(sizeof(node));
    //assign data to data and initialize pointer to NULL
}

void deleteNode(List *list, Node *node){
    //Take care of the next pointer
    free(node);
}

当我释放节点,我必须删除结构(数据和下一个指针)的成员呢?由于我不是用malloc专门为会员,但只适用于整个结构?如果是的话我怎么办呢?将在节点的所有成员被放置在堆上,堆栈根本不会使用?

When I free the node, do I have to delete the members of the struct (data and next pointer) as well? Since I am not using malloc specifically for the members, but only for the entire struct? If so then how do I do it? Will all the members of the node be placed on the heap, and the stack will not be used at all?

推荐答案

最终的规则:你免费()相同数量的时候,你的malloc() (或释放calloc(),或...)

The ultimate rule: you free() exactly the same number of times you malloc() (or calloc(), or...)

所以:

我。如果数据指向这些函数分配的东西,那么是的,你必须这样做。

I. If the data points to something allocated by these functions, then yes, you need to do so.

二。 于节点>接下来是要释放的过程(假设你正在使整个列表),所以你总有需要释放它,但你只有在采取下一个元素的照顾。

II. node->next is to be freed of course (assuming you are freeing the entire list), so you need to free it anyway, but only after you have taken care of the next element.

迭代求解:

void free_list(Node *list)
{
    while (list != NULL) {
        Node *p = list->next;
        // maybe:
        // free(list->data);
        free(list);
        list = p;
    }
}

一个递归解决方案:

void free_list(Node *list)
{
    if (list->next != NULL) {
        free_list(list->next);
    }

    // free(list->data);
    free(list);
}

这篇关于在C结构使用免费的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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