free memomy of link list

Hi everyone,
I have two structure A & B.
1
2
3
4
5
6
7
8
9
10
11
struct B
{
 int h,w;
 double d;
 struct B *next,*prev;
};

struct A
{
 struct B *st;
};


In my main code

1
2
 struct A str;
 allocate_mem(&str);


In allocate_mem

1
2
3
4
 if(str->st == NULL)
 {
  str->st = (B*)malloc(sizeof(B);
 }


Now I want to free the memory.
I tried free(str.st) But it is not working. Memory leakage wasw there.
Please tell me how to free the list.

thanks.
It seems like your allocate_mem function is checking if the member varibale pointer [st] of struct A is NULL before performing a malloc - you however don't seem to do anything to ensure that this value is NULL when an instance of [A] is created. This then implies that function allocate_mem most likely saw that str->st was not NULL (had some unitialized value) and consequently did no malloc for str->st.

The call then to free(str.st) probably called free on some illegal memory (the unitialized value of st).

Maybe you should add a constructor to struct A that initializes st to NULL.

1
2
3
4
5
6
struct A
{
   A() : st(NULL) {}
 
   struct B *st;
};


Even better - add a destructor for struct A to free st automatically.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct A
{
   A() : st(NULL) {}
   
   ~A()
   {
      if (st)  
      {
         free(st);
      }
   }
 
   struct B *st;
};
I suspect bibhukalyana is writing in C so a constructor and destructor is not possible. You don't need to check if a pointer is null before calling free on it. free(NULL); is safe and will do nothing.

How do you know there is a memory leak? If str->st->next and str->st->prev is pointing to something are freeing that memory somewhere?
Or even better: both. A wild pointer should always be assigned a 0 [in my opinion], both when initialized and after delete is called.
Please correct me if I am wrong here - I haven't worked in pure c for a long time now:

If we create a new instance of struct [A], then what will the initial value of member [st] be?

From my experience, I would have thought that st would have some garbage value.

free(NULL) may be safe but free(abc)

where abc is pointing to something unitialized (ie garbage) may not be.

If [st] indeed has some garbage value, then would it still be safe to call free on it?
Indeed, it will be garbage. Also, I'm not even sure if free checks for 0 or not. delete does though.
Topic archived. No new replies allowed.