Freeing array of structs inside struct

允我心安 提交于 2019-12-24 08:38:43

问题


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);
}

回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/40950900/freeing-array-of-structs-inside-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!