Saturday, 31 August 2013

freeing memory in nested data structure

freeing memory in nested data structure

I have a struct A
struct A {
void *content;
short flag;
...
}
I am dynamically allocating memory using malloc , and i have written a
function to free memory like this
void destroy()
{
struct A *tmp = HEAD; //global
struct A *buf;
while(NULL != tmp) {
buf = tmp;
tmp = tmp->next;
if( //buf->flag is of some type) { //the if part
some_struct *s = (some_struct*)buf->content;
free(s);
}
free(buf);
}
}
This code is resulting in segfault. but if i remove the "if" part in while
loop it then its working fine but results in leak.

No comments:

Post a Comment