Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The 4 bytes most likely contains the total number of objects in the allocation so delete [] will be able to loop over all objects in the array calling their destructor..</p> <p>To get back the original address, you could keep a lookup-table keyed on address / 16, which stores the base address and length. This will enable you to find the original allocation. You need to ensure that your allocation+4 doesn't cross a 16-byte boundary, however.</p> <p>EDIT: I went ahead and wrote a test program that creates 50 objects with a destructor via new, and calls delete []. The destructor just calls printf, so it won't be optimized away.</p> <pre><code>#include &lt;stdio.h&gt; class MySimpleClass { public: ~MySimpleClass() {printf("Hi\n");} }; int main() { MySimpleClass* arr = new MySimpleClass[50]; delete [] arr; return 0; } </code></pre> <p>The partial disassembly is below, cleaned up to be a bit more legible. As you can see, VC++ is storing array count in the initial 4 byes.</p> <pre><code>; Allocation mov ecx, 36h ; Size of allocation call scratch!operator new test rax,rax ; Don't write 4 bytes if NULL. je scratch!main+0x25 mov dword ptr [rax],32h ; Store 50 in first 4 bytes add rax,4 ; Increment pointer by 4 ; Free lea rdi,[rax-4] ; Grab previous 4 bytes of allocation mov ebx,dword ptr [rdi] ; Store in loop counter jmp StartLoop ; Jump to beginning of loop Loop: lea rcx,[scratch!`string' (00000000`ffe11170)] ; 1st param to printf call qword ptr [scratch!_imp_printf; Destructor StartLoop: sub ebx,1 ; Decrement loop counter jns Loop ; Loop while not negative </code></pre> <p>This book keeping is distinct from the book keeping that malloc or HeapAlloc do. Those allocators don't care about objects and arrays. They only see blobs of memory with a total size. VC++ can't query the heap manager for the total size of the allocation because that would mean that the heap manager would be bound to allocate a block exactly the size that you requested. The heap manager shouldn't have this limitation - if you ask for 240 bytes to allocate for 20 12 byte objects, it should be free to return a 256 byte block that it has immediately available.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload