
free()'ing structs containing pointers to memory?
Quote:
>What happens to memory referenced by pointers which are part of a
>struct, when that struct is freed?
>for example if I ...
>------------------------------------------------------
>typedef struct
>{
> char foo[27];
>} FOOSTRUCT;
>typedef struct
>{
> char bar[27];
> FOOSTRUCT *x;
>} BARSTRUCT;
>BARSTRUCT *bar=calloc(sizeof(BARSTRUCT),1);
>... code involving bar ...
>free(bar);
>---------------------------------------------------------------
>Is there still memory allocated somewhere for bar->x?
No. when you call malloc (and friends) you get a pointer to a block of
memory. When you pass that pointer to free() that whole block of memory
is freed. In this case you allocated memory for a struct. When you call
free that whole struct is freed. Any pointers you have to parts of that
struct are then invalid - you may no longer use their values.
However note that in the example above you have only allocated a structure
of type BARSTRUCT which has a member x which has type pointer to FOOSTRUCT.
You have *not* however allocated any memory for any FOOSTRUCT object. bar->x
is in effect an uninitialised pointer (calloc does not guarantee that it is
a null pointer) and you need to set it to point to a valid FOOSTRUCT object
before you can dereference it. To do that you might call malloc/calloc
again to allocate space for a FOOSTRUCT object. Then to free the
datastructures you would have to call free twice. Remember malloc/calloc
allocates one object and free frees one object. To release all memory so
allocated you need to call free the same number of times that you called
malloc/calloc (assuming that there were no failures, which, incidentally
you should test for, and of course realloc can do various things).
Quote:
>In other words, does this constitute a memory leak, requiring me
>to first free(bar->x) before I free(bar)?
You must only free(bar->x) if bar->x points to an object created
by malloc/calloc/realloc. (You can also pass a null pointer to free in
which case it does nothing).
--
-----------------------------------------
-----------------------------------------