Carpetfizz Carpetfizz - 3 years ago 98
C Question

When do nondynamic arrays get free'd in a struct

I have the following


typedef struct {
int id;
double c[2];
double p[4][2];
} Detection;

This is the constructor for it

Detection* create_detection(int i) {
Detection* detection = (Detection*) malloc(sizeof(Detection));
detection->id = i;
return detection;

As you can see, the struct itself is dynamically allocated. I'm trying to write a destructor for it and this is what I have so far.

void destroy_detection(Detection* detection) {

Will this free
as well?

Answer Source

There is only one allocation here. The c and p fields do not have separate allocations. The general rule is each call to malloc must be balanced, one to one, by a call to free. The destructor as written is all that is needed. If there were other dynamically allocated pointers inside the struct, additional free calls might be required.

Note that the c and p fields have fixed size, which is included in sizeof(Detection). In C++ fields can have their own constructors which can do dynamic allocation, but they will also typically be automatically destructed from code the compiler generates in the parent destructor.

C has variable length arrays (VLAs) but they cannot be declared in a struct, only in a function argument list or in a block inside a function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download