How does delete[] know how much memory to delete? [duplicate]

☆樱花仙子☆ 提交于 2019-12-13 04:35:42

问题


int* i = new int[4];
delete[] i;
  1. While we call delete[], how does the program know "i" is 4 byte-length. Is 4 be stored in somewhere in memory?
  2. The implementation of delete[] depend on System or Compilers?
  3. Is there some System API to get the length of i?

As HadeS said, which will hold the information how much memory has been allocated? And where? It must be hold in memory, or maybe nearby the pointer i.


回答1:


First off, i is not "4-byte length". Rather, i is a pointer to an array of four ints.

Next, delete[] doesn't need to know anything, because int has no destructor. All that has to happen is that the memory needs to be freed, which is done by the system's allocator. This is the same situation as with free(p) -- you don't need to tell free how much memory needs to be freed, since you expect it to figure that out.

The situation is different when destructors need to be called; in that case, the C++ implementation does indeed need to remember the number of C++ objects separately. The method for this is up to the implementation, although many compilers follow the popular Itanium ABI, which allows linking together of object code compiled by those different compilers.

There is no way for you to query this information. You should consider dynamic arrays a misfeature of C++; there is essentially no reason to use them*, and you can always do better with some kind of class that manages memory and object separately and individually: Since you'll have to remember the number of array elements anyway, it's much better to encapsulate the size and the allocation in one coherent class, rather than have vague dynamic arrays that you cannot really use without passing extra information along anyway (unless you had self-terminating semantics, but then you'd just be using the extra space for the terminator).

*) And there are at least two standard defects about dynamic arrays that nobody is too bothered to worry about fixing




回答2:


When you dynamically allocate a memory; compiler allocates an extra block of memory apart from what you have asked, which will hold the information how much memory has been allocated. when you try to delete this memory using delete this extra block of memory will be read by the compiler to see how much memory was allocated and free the space accordingly.

I don't think there is any API which will fetch this information.



来源:https://stackoverflow.com/questions/21983838/how-does-delete-know-how-much-memory-to-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!