I have two structs
struct obj_t {
int id;
float x;
float y;
};
struct cluster_t {
int size;
int capacity;
struct obj_t *obj;
};
As you can see, there is pointer to first obj_t
inside cluster_t
What I want to do is to free every obj_t from array inside cluster_t
Do I have to write it with for
loop like this?
void clear_cluster(struct cluster_t *c)
{
for(int i = 0; i<c->size;i++)
{
free(&c->obj[i]);
}
free(c->obj);
}
Or is it ok to free the memory just like this ?
void clear_cluster(struct cluster_t *c)
{
free(c->obj);
}
There should be one free()
for every malloc()
you have, and executed in the opposite order from which it was allocated.
The field obj
of cluster_t
is a pointer to an array of object_t
. This is probably allocated with one malloc()
when initializing your cluster_t
(something like c->obj = malloc(c->capacity*sizeof(*c->obj))
), so it only needs to be freed with one call to free()
. You would then want to free the cluster_t
allocation itself (assuming it too was dynamically allocated):
free(c->obj);
free(c);
There would be a difference, however, if each object_t
itself had a dynamic allocation within it. (In your example, object_t
does not.) In that case, you would have needed to iterate through the array and malloc()
an allocation when you created the array, and therefore do the reverse and free()
each at the end.