Car*_*izz 3 c malloc free struct memory-management
我有以下内容 struct
typedef struct {
int id;
double c[2];
double p[4][2];
} Detection;
Run Code Online (Sandbox Code Playgroud)
这是它的构造函数
Detection* create_detection(int i) {
Detection* detection = (Detection*) malloc(sizeof(Detection));
detection->id = i;
return detection;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,struct本身是动态分配的.我正在尝试为它编写析构函数,这是我到目前为止所做的.
void destroy_detection(Detection* detection) {
free(detection);
}
Run Code Online (Sandbox Code Playgroud)
请问这种自由c和p呢?
这里只有一个分配.该c和p字段没有独立的分配.一般规则是每次呼叫malloc必须通过呼叫一对一地平衡free.编写的析构函数就是所需要的.如果struct中有其他动态分配的指针,则free可能需要额外的调用.
请注意,c和p字段具有固定大小,包含在中sizeof(Detection).在C++中,字段可以有自己的构造函数,可以进行动态分配,但它们通常也会自动从编译器在父析构函数中生成的代码中进行破坏.
C具有可变长度数组(VLA),但它们不能在结构中声明,只能在函数参数列表或函数内的块中声明.