3

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

A random thought occured to me that how comes free(myPtr) doesn't need a length parameter? How does it know how much memory to free?

I can only guess that it keeps track of how much memory it allocates for each particular start address.

Community
  • 1
  • 1
gcb
  • 366
  • 5
  • 16

2 Answers2

8

This is because malloc saves the information about the length of the allocated chunk, usually in a spot that precedes the address returned to your program. It is not unusual for implementations to allocate an extra storage for a size_t, put the size there, add sizeof(size_t), and return it to you as the malloc-ed pointer. The standard does not call for this implementation, thoug, so alternative implementations are possible, e.g. based on a hash table.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Also, it's easier as well as preventing developer problems of keeping track of the length of the chunks. – Rivasa Aug 10 '12 at 00:51
  • 1
    I have also read about a method for allocating small objects: you can have several "zones" - each contains only objects of a specific size, so free can figure out the size by checking in which zone the freed memory is located. – Gir Aug 10 '12 at 00:55
3

When C allocates memory, it records the length associated with the pointer it gives you. (Often in the area just before the block of memory. But that's an implementation detail.) It keeps some kind of table or list of memory blocks it's handed out, and when you free that memory, C looks up the length of that block based on the value of the pointer.

That's part of why the pointer you pass to free has to be exactly equal to the one you get back from malloc. If it's not, C gets confused and can't find the correct memory block (or its length), and may very well end up "freeing" some memory it was never meant to touch. (If it does that, you may end up with a condition called "heap corruption", which is really bad -- from then on, C might do all kinds of wacky stuff, like trying to allocate some memory in the middle of an existing block and mangling whatever's there.)

cHao
  • 84,970
  • 20
  • 145
  • 172