2

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.?

0

6 Answers 6

5

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

4

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).

Comments

1

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.

Comments

1

The simple way to think about it is that every malloc must have a corresponding free. If you malloc a structure that holds pointers to other malloc'ed items, freeing that structure does not free the other items pointed to. Those other items must be freed at some point to not leak memory.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.