[英]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: 我的Free()包装器是:
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. 我无法释放指向结构Struct的指针。 This is my question: how do I free the location
struct pointed to by location *loc;
这是我的问题:如何释放由location *loc;
指向的location
结构location *loc;
I used a wrapper of free()
as these are node's in a generic linked list. 我使用了free()
的包装,因为这些是通用链接列表中的节点。
The free
function takes a void*
as parameter, so that cast doesn't count. free
函数将void*
作为参数,因此强制转换不计算在内。 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: 在释放observer
之后,您不能释放loc
,但是在释放它之前, loc
是一个公平的游戏:
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
. 当然,这假设您要在void* data
内部传递指向observer
的指针。 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
. 由于将指针的指针传递到释放指针的函数的唯一有效理由是将指针设置为NULL
,因此我在最后一行添加了*p
。
It is not clear, however, why you pass void *
instead of observer **
. 但是,不清楚为什么传递void *
而不是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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.