eitharus
eitharus

Reputation: 15

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.

Upvotes: 1

Views: 2086

Answers (3)

D3Hunter
D3Hunter

Reputation: 1349

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

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

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

Upvotes: 2

Paul92
Paul92

Reputation: 9062

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

Upvotes: 2

Related Questions