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

前端 未结 9 1492
-上瘾入骨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:13

    It's defined in the C++ standard to be compiler specific. Which means compiler magic. It can break with non-trivial alignment restrictions on at least one major platform.

    You can think about possible implementations by realizing that delete[] is only defined for pointers returned by new[], which may not be the same pointer as returned by operator new[]. One implementation in the wild is to store the array count in the first int returned by operator new[], and have new[] return a pointer offset past that. (This is why non-trivial alignments can break new[].)

    Keep in mind that operator new[]/operator delete[]!=new[]/delete[].

    Plus, this is orthogonal to how C knows the size of memory allocated by malloc.

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

    The information is not standardised. However in the platforms that I have worked on this information is stored in memory just before the first element. Therefore you could theoretically access it and inspect it, however it's not worth it.

    Also this is why you must use delete [] when you allocated memory with new [], as the array version of delete knows that (and where) it needs to look to free the right amount of memory - and call the appropriate number of destructors for the objects.

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

    This isn't something that's in the spec -- it's implementation dependent.

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

    It is not standardized. In Microsoft's runtime the new operator uses malloc() and the delete operator uses free(). So, in this setting your question is equivalent to the following: How does free() know the size of the block?

    There is some bookkeeping going on behind the scenes, i.e. in the C runtime.

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

    Basically its arranged in memory as:

    [info][mem you asked for...]

    Where info is the structure used by your compiler to store the amount of memory allocated, and what not.

    This is implementation dependent though.

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

    When you allocate memory on the heap, your allocator will keep track of how much memory you have allocated. This is usually stored in a "head" segment just before the memory that you get allocated. That way when it's time to free the memory, the de-allocator knows exactly how much memory to free.

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