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?