1

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

Hi,

When using malloc(), we specify the size of the allocation, so it knows how much to allocate. However, how does free() knows how many bytes to release? The pointer contains only the starting address of the memory block, not the length of memory block.

Thanks and Regards, Tazim.

Community
  • 1
  • 1
tazim
  • 133
  • 1
  • 2
  • 7

4 Answers4

4

The answer to this is implementation-dependent; the malloc library keeps track of the length somehow, but exactly how it does so is not specified by the C language standard.

A typical approach is to store some header information (including length) before the "starting address" that malloc returns to the caller.

David Gelhar
  • 27,873
  • 3
  • 67
  • 84
2

Malloc saves the size of the allocated pointer in some kind of data structure. When you call free it looks up the entry in this data structure and free's that much memory.

GWW
  • 43,129
  • 11
  • 115
  • 108
0

When you allocate memory, the run-time library also maintains some internal structures. It has to in order to keep track of what parts of the heap have been allocated. This information also tells it the size of a block of memory given a pointer to that memory.

It depends on the implementation but there's a good chance this information is stored just before the pointer returned.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
0

It's implementation-specific. Some techniques:

  • There may be more than one pointer. An arbitrarily complex structure could be allocated and you just get a pointer to the user-payload area. The library knows the fixed offset between the pointer given to you and the pointer to the origin of the structure. The other fields could be the size and the links that thread free blocks together.

  • There may be a separate dictionary. This can have memory-management advantages. One problem with using the allocated block for book-keeping is that the library itself ends up writing to many if not most of the allocated pages. This keeps them dirty (in an MMU sense) and can also prevent them from being shared following a fork. This is a big problem for web servers and has led to specialized implementations of web language systems ("Ruby Enterprise") that differ mainly in memory management core.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329