0

Possible Duplicate:
C programming : How does free know how much to free?

How does free() know how much memory to be free'd which was earlier allocated by malloc() or calloc()? I mean, both of these functions receive size as parameters, while free only needs the pointer to allocated memory. Then how does free() know that how much to free?

Community
  • 1
  • 1

3 Answers3

1

The C standard mandates that the same address returned by malloc be passed to free to deallocate the dynamic memory, So it is clear that malloc maintains some kind of table or mapping for each allocated address (mind you, exact details are unspecefied) where it stores the size of the allocated memory against the address and so it knows exactly how much memory was allocated for every address it returned back to its callers. In a free call it would lookup this mapping to know how much memory to deallocate.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

You don't need to know.

It could use any mechanism, it's up to the folks implementing the standard library to decide.

A typical approach is to store block information somewhere just before the pointer returned to the application, but you could also use a totally separate data structure to keep track of allocations, perhaps some kind of tree where the pointer is used as a key to look for information describing that allocation.

If you really want to know, to learn, you can of course read the source code for open sourced C standard library implementations, of which there are at least a couple.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

Generally, you have in the free store something like a linked list of allocated resources. The memory manager is going to search that list for the memory block, remove it from the list of allocated resources and insert it back to free resources allowing it to be called again by the allocation functions. How this is done depends on the compiler implementation.

Mansuro
  • 4,558
  • 4
  • 36
  • 76