Skip to main content
GameDev.net gamedev.net
🔒 Locked

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

Started by Tispe Dec 14, 2011 at 9:21 AM 4 replies 1.5k views
Original Post
Tispe
Tispe
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?
RulerOfNothing
RulerOfNothing
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.
BenjaminSergent
BenjaminSergent
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.
Yang G
Yang G
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.
Tispe
Tispe
any differance in new or malloc, besides new->delete and malloc->free() ?
Evil Steve
Evil Steve

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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.