How does delete[] know the size of an array?

后端 未结 8 1148
面向向阳花
面向向阳花 2021-01-02 01:51

I am curious how delete[] figures out the size of the allocated memory. When I do something like:

int* table = new int[5];
delete[] table;

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-02 02:38

    How this is done is a compiler specific detail. But the call to delete[], assuming no memory corruption, will always delete the right number of elements. There are several ways to achieve this but one simple way is to hide the length in the memory.

    Here's a nice and simple way to implement this for demonstration purposes. Say your code calls new int[10]. Instead of allocating 10 * sizeof(int), the compiler allocates (10 * sizefo(int))+sizeof(size_t). It then returns a pointer to you which is offset size_t from the start. Inside that initial size_t space it writes the number 10. Now when you call delete[] and pass in a pointer, the compiler just goes backward size_t bytes and finds the number of elements to delete.

提交回复
热议问题