No. free
won't do recursive free for all members. You have to explicitly free all members for which you have allocated memory.
If you understand how memory is allocated for struct and how free works this won't be a problem.
struct mystr {
char * strp,
unsigned int foo,
};
when you allocated memory using malloc & friends, it only allocates memory for the members.
In your case one char*
and one unsigned int
. Note that it doesn't allocate any memory for storing data in the char*
. So you have to allocate memory for strp
again before storing data. Except when you directly assign string literals Or just use the pointer strp
to point to an existing memory.
Example:
case 1:
struct mystr s;
s.strp = "literals"; // valid, no need to malloc
case 2:
char *p="abc";
s.strp = p; // valid, no need to malloc
On all other usages, you must allocate memory for strp
before storing data into strp
.
So when you call free
on the struct variable, it only frees the pointer allocated for strp
and not the memory which is pointed to by strp
.
It's simply because free
has no information about where strp
points to.
Note that in the above two examples, you don't free strp
as you didn't allocate any memory there for storing data into strp
. Simple rule is one free for one malloc/calloc/realloc
.