How does delete[] “know” the size of the operand array?

前端 未结 9 1507
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:50
Foo* set = new Foo[100];
// ...
delete [] set;

You don\'t pass the array\'s boundaries to delete[]. But where is that information stor

相关标签:
9条回答
  • 2020-11-22 03:24

    This is a more interesting problem than you might think at first. This reply is about one possible implementation.

    Firstly, while at some level your system has to know how to 'free' the memory block, the underlying malloc/free (which new/delete/new[]/delete[] generally call) don't always remember exactly how much memory you ask for, it can get rounded up (for example, once you are above 4K it is often rounded up to the next 4K-sized block).

    Therefore, even if could get the size of the memory block, that doesn't tell us how many values are in the new[]ed memory, as it can be smaller. Therefore, we do have to store an extra integer telling us how many values there are.

    EXCEPT, if the type being constructed doesn't have a destructor, then delete[] doesn't have to do anything except free the memory block, and therefore doesn't have to store anything!

    0 讨论(0)
  • 2020-11-22 03:33

    Because the array to be 'deleted' should have been created with a single use of the 'new' operator. The 'new' operation should have put that information on the heap. Otherwise, how would additional uses of new know where the heap ends?

    0 讨论(0)
  • 2020-11-22 03:36

    ONE OF THE approaches for compilers is to allocate a little more memory and to store a count of elements in a head element.

    Example how it could be done:

    Here

    int* i = new int[4];
    

    compiler will allocate sizeof(int)*5 bytes.

    int *temp = malloc(sizeof(int)*5)
    

    Will store "4" in the first sizeof(int) bytes

    *temp = 4;
    

    and set i

    i = temp + 1;
    

    So i will points to an array of 4 elements, not 5.

    And deletion

    delete[] i;
    

    will be processed in the following way:

    int *temp = i - 1;
    int numbers_of_element = *temp; // = 4
    ... call destructor for numbers_of_element elements
    ... that are stored in temp + 1, temp + 2, ... temp + 4 if needed
    free (temp)
    
    0 讨论(0)
提交回复
热议问题