Free() pointer to Struct, inside a Struct

≯℡__Kan透↙ 提交于 2019-12-11 13:11:17

问题


I can't seem to find how to free() the sub struct.

Structs:

typedef struct
{
    char ID[5];
    location *loc;
} observer;

typedef struct
{
    double lat;
    double lng;
} location;

My Wrapper of Free() is:

void free_obs_list_node(void *data)
{
    free(*(observer **)data);
}

I can free the observer struct. I cannot free the pointer to the location Struct. This is my question: how do I free the location struct pointed to by location *loc;

I used a wrapper of free() as these are node's in a generic linked list.


回答1:


The free function takes a void* as parameter, so that cast doesn't count. You just need to give a pointer to the memory location you want to free:

free(data->loc);



回答2:


You cannot free loc after you have freed the observer, but before you freed it loc is a fair game:

void free_obs_list_node(void *data) {
    observer **p = data;
    free((*p)->loc);
    free(*p);
    *p = NULL;
}

Of course this assumes that you are passing a pointer to a pointer to observer inside the void* data. Since the only valid reason to pass a pointer to pointer into a function that frees the pointed to pointer is to have the pointer set to NULL, I added the last line to null out *p.

It is not clear, however, why you pass void * instead of observer **.




回答3:


You should make sure data is not null in you code, or you can easily got a segment fault when accessing a null pointer.

I do not understand why you use a double pointer, it makes code much more complex and bug prone. Code below should work:

void free_obs_list_node(void *data)
{
    observer **ob = (observer **)data;// do not understand why you use a double pointer, it makes code much more complex and bug prone
    if(NULL == ob || NULL == *ob)
        return;
    if(NULL != (*ob)->loc)
        free((*ob)->loc);
    free(*ob);
}


来源:https://stackoverflow.com/questions/27382159/free-pointer-to-struct-inside-a-struct

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