Jump to content

  • Log In with Google      Sign In   
  • Create Account

How does delete[] know how many bytes to release?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
5 replies to this topic

#1 Tispe   Members   -  Reputation: 1034

Like
0Likes
Like

Posted 14 December 2011 - 03:21 AM

Say I read a file from disk to a char* pBuffer in one function, then pass the pBuffer to another function where it is delete[]'d. How does the "delete[] pBuffer" operattion know how many bytes to release? Is there a "end of block" byte at the end or does the OS know?

Sponsor:

#2 RulerOfNothing   Members   -  Reputation: 1160

Like
0Likes
Like

Posted 14 December 2011 - 03:27 AM

The way the code knows how many bytes to release is implementation-dependent, but I recall it usually being stored at the front of the memory block.

#3 Labouts   Members   -  Reputation: 133

Like
1Likes
Like

Posted 14 December 2011 - 03:36 AM

Ruler is right: there are two main methods, one is storing the size at the head and the other is maintaining a hashtable which associates pointer P with size N. Which one is used depends on the compiler.
See this for more information.

#4 Yang G   Members   -  Reputation: 105

Like
0Likes
Like

Posted 14 December 2011 - 03:36 AM

In fact, while you new or malloc a range of memory, there is a header block who will record these information used to release the memory.

#5 Tispe   Members   -  Reputation: 1034

Like
0Likes
Like

Posted 14 December 2011 - 08:21 AM

any differance in new or malloc, besides new->delete and malloc->free() ?

#6 Evil Steve   Members   -  Reputation: 1982

Like
0Likes
Like

Posted 14 December 2011 - 08:59 AM

any differance in new or malloc, besides new->delete and malloc->free() ?

Operator new will call the constructor for an object, whereas malloc will not. You could use malloc and then placement new and get the same effect as if you had just allocated the memory with new (Except you need to free the memory with free() rather than delete, and need to manually call the destructor first).

Operator new is usually implemented as a call to malloc() internally.

Steve Macpherson
Systems Programmer

Rockstar North





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS