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

bnd*_*bnd 3 c pointers

我很久没有使用过C了,我还是有些新手.我对指针和引用的语法感到困惑.基本上我有一个带有指针的struct容器,我将其动态分配为数组.当我完成它时,我想知道如何释放内存.这是它的样子:

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;
}
Run Code Online (Sandbox Code Playgroud)

我收到一个编译器错误,告诉我我正在从一个不是结构的东西请求一个成员.但是我认为传递一个Ref*derefred所以它就像传递结构一样.我正在使用gcc和ANSI C.

Pau*_*aul 7

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 *
}
Run Code Online (Sandbox Code Playgroud)

由于您想要修改指向结构栏的指针(将指针设置为NULL),因此传入BarRef*是正确的,但过程的内容应如下所示:

free((*B)->foo);
(*B)->foo = NULL;
free(*B);
*B = NULL;
Run Code Online (Sandbox Code Playgroud)

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

(*B)dereferences B,给你一个BarRef(AKA a Bar *) (*B)->foo访问foo指向的bar结构中调用的元素(*B)

B->foo是无效的.它意味着访问在foo指向的bar结构中调用的元素B.既然B没有指向一个条形结构,而是指向一个pointer to a bar structure你得到"请求一个不是结构的东西的成员"错误."不是结构的东西"是指向结构的指针.