0

Possible Duplicates:
How does delete work in C++?
C programming : How does free know how much to free?

For every dynamic memory allocation, using 'malloc / new', we have methods, 'free / delete' to free the allocated memory.

My question is if the memory allocation size is decieded at runtime and the memory locations not being contiguous, how does these memory freeing methods know how much memory to free and what are the memory locations to be cleared ?

What makes these functions work if we are passing them only a pointer to single location ?

Community
  • 1
  • 1
Mandar
  • 693
  • 2
  • 9
  • 19

2 Answers2

0

They keep track of how much memory you've allocated where internally.

user541686
  • 205,094
  • 128
  • 528
  • 886
0

When malloc/new allocates memory it also records where and how much memory it allocated for a pointer to a given memory location. free/delete looks up what memory to deallocate when you give it a pointer.

That is why you should never try to free a pointer that you moved with "+=" or something like that.

trutheality
  • 23,114
  • 6
  • 54
  • 68
  • Note, there don't need to be "tables". It's possible to just store a chunk's size with the chunk, for example right before the address that's returned, and to consider the heap as just a linked list of such chunks. The actual method of keeping track of that stuff is highly implementation-dependent, which is part of why it's undefined behavior to free/delete any pointer other than the one you got from malloc/new. – cHao Jun 23 '11 at 04:29