简体   繁体   English

如何从结构中释放动态分配的内存?

[英]How do I free a dynamically allocated memory from inside a struct?

I haven't used C in a long while, and I'm still somewhat new to it. 我很久没有使用过C了,我还是有些新手。 I'm confused by the syntax for pointers and references. 我对指针和引用的语法感到困惑。 Basically I have a struct container with pointers that I am dynamically allocating as arrays. 基本上我有一个带有指针的struct容器,我将其动态分配为数组。 I want to know how to free up that memory when I'm done with it. 当我完成它时,我想知道如何释放内存。 Here's what it looks like: 这是它的样子:

typedef struct {
    int* foo;
} Bar;

typedef Bar * BarRef;

BarRef newBar(int n) {
    BarRef B = malloc(sizeof(Bar));
    B->foo = calloc(n,sizeof(int));
}

/* This is what I am having trouble understanding */
void freeBar(BarRef *B) {
    free(B->foo);
    B->foo = NULL;
    free(B);
    *B = NULL;
}

I get a compiler error telling me that I am requesting a member from something that is not a struct. 我收到一个编译器错误,告诉我我正在从一个不是结构的东西请求一个成员。 But I thought passing a Ref* would derefrence so It would be like passing the struct. 但是我认为传递一个Ref*会降低,所以就像传递结构一样。 I'm using gcc and ANSI C. 我正在使用gcc和ANSI C.

void freeBar(BarRef * B) {
    // Here B is a pointer to a pointer to a struct Bar. 
    // Since BarRef is Bar *
    // And B is a BarRef *
}

Since you want to modify a pointer to a struct Bar (setting the pointer to be NULL) you are correct in passing in a BarRef *, but the contents of your procedure should look like this: 由于您想要修改指向结构栏的指针(将指针设置为NULL),因此传入BarRef *是正确的,但过程的内容应如下所示:

free((*B)->foo);
(*B)->foo = NULL;
free(*B);
*B = NULL;

(*B)->foo works as follows: (*B)->foo工作原理如下:

(*B) dereferences B, given you a BarRef (AKA a Bar * ) (*B)->foo accesses the element called foo in the bar structure pointed to by (*B) (*B)取消引用B,给你一个BarRef (AKA a Bar *(*B)->foo访问由(*B)指向的条形结构中名为foo的元素

B->foo is invalid. B->foo无效。 It means access the element called foo in the bar structure pointed to by B . 它意味着访问B指向的bar结构中名为foo的元素。 Since B doesn't point to a bar structure, but instead points to a pointer to a bar structure you get the "requesting a member from something that is not a struct" error. 由于B不指向条形结构,而是pointer to a bar structurepointer to a bar structure您将获得“从不是结构的东西请求成员”错误。 The "something that is not a struct" is a pointer to a struct. “不是结构的东西”是指向结构的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM