Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
C programming free() function - does it really not need a size argument?
When you get heap memory with malloc, you have to use a size argument. To release the memory with free(), apparently you just use the pointer. Does this really release the memory from, say, a large structure pointer, and not just the first byte?
Thanks Tony - that is what I was hoping for - I just didn't believe it was that simple.
2 Answers
- tony1athomeLv 51 decade agoFavorite Answer
No, it doesn't need an argument. A good implementation will be able to recognize the block of memory being freed and the internal bookkeeping created during the malloc() will be used by free() to determine the size of the allocated block.
Yes, when you free a pointer, you're implicitly freeing ALL of the memory that you allocated when you malloc()'ed and received that pointer.
You should only be free()'ing pointers that were returned by malloc().
- sofarsogoodLv 51 decade ago
If you go into the implementation, when you call x = malloc(1000) you get a pointer to 1000 free bytes. Actually, the system allocates more than 1000 bytes. At the fromt of this, location x - (something), there is a memory structure that the OS uses for bookkeeping. When you free(x) the OS retrieves that structure, so it knows how much memory is allocated at x.