-3

I want to understand how free() works. In the example below, how does free() know how many bytes are in the block it needs to free?

#include <stdlib.h>

int main()
{     
    char *p= NULL;
    int size = 25;
    p = (char *)malloc(size);

    /* some operation on p */

    free(p);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
jinal shah
  • 122
  • 4
  • 1
    people should not downvote duplicate question. Duplicate question doesnot means that its a low quality question it means that someone other has already asked such question. Asker didnot have searched before posting this question. – Jeegar Patel Jun 12 '13 at 04:58
  • @Mr.32 When you hover over the downvote, it'll show you a context tip: "This question does not show any research effort; it is unclear or not useful". That sounds fairly accurate, to me. *CLICK*! – autistic Jun 12 '13 at 05:14

1 Answers1

2

That's implementation specific, the only thing defined is how it should look like it works to the application, and the implementation is free to use whatever structure it needs to give good performance/low memory use/...

As an example, one way would be to reserve a few bytes before the block returned, and store the size there. For example, if you malloc() 25 bytes, it would actually reserve 29 bytes, store the size in the 4 first bytes and return a pointer to the last 25 bytes. free() can then take the pointer, subtract 4 and read the size.

Another way would be to store the address/size in a hash table, so that when someone calls free(), it can look the size up in the hash table.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294