如何释放仅包含指针的结构

如何释放仅包含指针的结构

本文介绍了如何释放仅包含指针的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在下面看到的结构:

I have a struct which you see below:

typedef struct _List {
    Person *person; // pointer for people list
    DoList *do; // Kinda timer, for checking list in some intervals
} List;

是否需要释放此结构?如果是这样,我该如何释放它?

Are there any need to free this struct? If so, how can i free it?

推荐答案

如果动态分配结构,则必须释放该结构.如果您动态分配成员并且在其他任何地方都没有对它们的引用,则必须在释放结构之前释放其成员.

You have to free the struct if you allocated it dynamically. You have to free its members before deallocating the struct if you allocated the members dynamically and don't have a reference to them anywhere else.

以下是一些示例:

void freeNotRequiredHere() {
    List            nonDynamicList;
    Person          nonDynamicPerson;
    DoList          nonDynamicDoList;

    nonDynamicList.person = &nonDynamicPerson;
    nonDynamicList.do = &nonDynamicDoList;
}


void freeRequiredForStructListOnly() {
    List            *dynamicList;
    Person          nonDynamicPerson;
    DoList          nonDynamicDoList;

    dynamicList = (List *) malloc( sizeof(struct List) );

    dynamicList->person = &nonDynamicPerson;
    dynamicList->do = &nonDynamicDoList;

    free( dynamicList );
}


void freeRequiredForStructListAndPersonOnly() {
    List            *dynamicList;
    Person          *dynamicPerson;
    DoList          nonDynamicDoList;

    dynamicList = (List *) malloc( sizeof(struct List) );
    dynamicPerson = (Person *) malloc( sizeof(Person) );

    dynamicList->person = dynamicPerson;
    dynamicList->do = &nonDynamicDoList;

    free( dynamicPerson );
    free( dynamicList );
}


void freeRequiredForStructListAndPersonOnly( DoList *notSureDoList ) {
    List            *dynamicList;
    Person          *dynamicPerson;

    dynamicList = (List *) malloc( sizeof(struct List) );
    dynamicPerson = (Person *) malloc( sizeof(Person) );

    dynamicList->person = dynamicPerson;
    dynamicList->do = notSureDoList;

    // maybe notSureDoList was allocated with malloc(),
    // maybe it is a non-dynamic stack variable.
    // the calling function should deal with free()'ing notSureDoList

    free( dynamicPerson );
    free( dynamicList );
}

这篇关于如何释放仅包含指针的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 21:10