Reputation: 744
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);
}
Upvotes: 1
Views: 913
Reputation: 7161
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.
Upvotes: 5
Reputation: 3538
It depends on how you allocated. It seems you did something like
struct cluster_t cluster;
cluster.obj = malloc(sizeof (struct obj_t) * SOMENUMBER);
in this case, cluster.obj
is just a pointer to an array. All you need to do is
free(cluster.obj)
or
free(c->obj)
in that function which receives a pointer to c
.
You only have to iterate over the array calling free
if you have an array of pointers.
Remember that &
takes the memory address of the variable. You don't free the pointer, you free the memory that the pointer points to. You will never do something like free(&pointer)
.
Upvotes: 2