如果我有一个像这样的结构:
struct Cell
{
unsigned int *x, *y;
char flag;
};
Run Code Online (Sandbox Code Playgroud)
下面的构造函数和解构器是否足以安全地分配和取消分配内存?
// Constructor function.
struct Cell *Cell_new()
{
struct Cell *born = malloc(sizeof(struct Cell));
if (born == NULL)
return NULL;
born->x = NULL;
born->y = NULL;
born->flag = false;
return born;
}
// Deconstructor function.
// When called, use Cell_destroy(&cell);
char Cell_destroy(struct Cell **cell)
{
free(cell);
cell = NULL;
}
Run Code Online (Sandbox Code Playgroud)
它是否正确?
我不明白的一件事是,如果我这样做:
struct Cell *myCell = Cell_new();
Cell_destroy(&myCell);
Run Code Online (Sandbox Code Playgroud)
当我正在调用时destroy,它期望一个指针(指向指针的指针)的地址,但我正在为结构提供一个地址.
我的意思是
我的功能期望:
Pointer -> Pointer -> Tangible Object
我给的是什么:
Pointer -> Tangible Object
这有缺陷的逻辑吗?我一直在查这个问题,所以可以说我可能会让自己感到困惑.
将类型的参数传递struct Cell **给析构函数是正确的,因为此函数将更改指针的值.
因此,如果要释放对象并将指针设置为NULL,则可以编写:
void Cell_destroy(struct Cell **cell)
{
free(*cell);
*cell = NULL;
}
Run Code Online (Sandbox Code Playgroud)
请注意如何cell取消引用.