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

后端 未结 8 1142
面向向阳花
面向向阳花 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:46

    The mechanism is implementation-dependent, but it will not be "fooled", by you reassigning the pointer in your example. It will deallocate the array of size 9, just like you told it to (and in this case there will be a memory leak because the array of size 5 now has nothing pointing to it).

    0 讨论(0)
  • 2021-01-02 02:47

    It would delete an array of size 9. It deletes the array pointed to by the pointer.

    It is unspecified how the size information is stored, so each compiler may implement it in a different way, but a common way to do it is to allocate an extra block before the array. That is, when you do this:

    int* table = new int[5];
    

    it actually allocates an array of 6 integers, and stores the array size in the first element. Then it returns a pointer to the second element. So to find the size, delete[] just has to read table[-1], basically.

    That's one common way to do it, but the language standard doesn't specify that it must be done in this way. Just that it has to work.

    Another approach might be to use the address of the array as a key into some global hash table. Any method is valid, as long as it produces the correct results.

    0 讨论(0)
提交回复
热议问题