gpt4 book ai didi

c - 如何释放只包含指针的结构

转载 作者:太空狗 更新时间:2023-10-29 16:46:02 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

这里有一些例子:

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

关于c - 如何释放只包含指针的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4915369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com