Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does delete work? [duplicate]

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

How does delete know how many bytes it has to free? I read that there is some block before the actual pointer address that is returned by new which contains block address details.

Anyone here who knows how many bytes this block has or how the format of that block is?

like image 730
Vijay Avatar asked Mar 24 '11 06:03

Vijay


2 Answers

In general, this is implementation-dependent.

The way this is usually implemented is that new/malloc will allocate slightly more bytes than you asked for, and will use the extra bytes for some book-keeping: many times the allocated blocks will also be maintained in a linked-list, and so the extra bytes will be used to store the next/prev pointer, as well as the size of the block.

This is not mandatory, however. The new/malloc calls can just as well store your pointer and the block's size in, say, a map.

If you're interested in a specific implementation, you will have to provide more information (e.g. what runtime/compiler are you using?).

like image 54
telewin Avatar answered Oct 21 '22 23:10

telewin


new operator and malloc function handle memory in their own particular ways, so

  • if you allocated memory with 'new' uses 'delete'
  • if you allocated memory with 'malloc' uses 'free'
  • if you don't know how/who/where the memory have been allocated, don't free it

If you are bound to try to mess up with the inner workings of malloc or new (which seems to be your goal), you're doing it wrong ^^

like image 22
Monkey Avatar answered Oct 22 '22 00:10

Monkey