Okay, this is possibly a stupid question but here goes: In C, is it enough to just use free() on the pointer return by malloc, even though the memory-area allocated by malloc may be huge and might have been casted into different types and structs etc.?
Yes. The memory manager takes care of that. It knows how big the memory is, and as long as you don't write past the bounds of the malloc() size, it will be fine.
Adding to JoshD post, the "type" returned by malloc() is void*
-- so it is nothing but a raw address which you can type-cast it into any of "different types and struts". So, it is really ok to call free on it and it is going to release the same amount of memory you initially got by calling malloc.
Not only is it OK, but the only way to free a memory block allocated by malloc()
is to give the pointer returned by malloc()
to free()
.
As far as the issue of "might have been casted into different types and structs, etc." - there's no problem with that as far as malloc()
and free()
are concerned, as long as when you free the block there's nothing left actively using it. However, you might need to be concerned about other issues concerning casting into "different types and structs", such as alignement and aliasing issues - but malloc()
and free()
have no part in that (as long as you don't corrupt memory outside the allocated block).
Yes and No.
Yes: that allocation--whatever it's size and however you used it--will be freed.
No: if you stored pointers in there to other malloc
'ed allocations and don't have another copy of those pointers, freeing the original allocation without freeing the children first will be memory leak.
in addiction to dmckee post, you must think of how you build your structure: if it's something like a b-tree, a list. an array of pointer to other dinamically allocated structure, well, in this case you must FIRST free childrens (for example, child node of a b-tree) and than go back to the root (maybe recursively, depending on the structure). It's a very common mistake and it can cause lot of memory leak