简体   繁体   中英

Free() pointer to Struct, inside a Struct

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM