Saturday, May 22, 2010

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?

C programming free() function - does it really not need a size argument?
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().
Reply: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.


No comments:

Post a Comment