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;
I understand that the memory of the table is freed. But what would happen if I reassigned the pointer to some different table.
int* table = new [5];
int* table2 = new [9];
table = table2;
delete[] table;
Will I free a table of the size 5 or 9? I am interested in how new[] and delete[] share information about their size. Or maybe I am missing something essential here.
Delete[] operator is used to deallocate that memory from heap. New operator stores the no of elements which it created in main block so that delete [] can deallocate that memory by using that number.
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.
Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. Delete can be used by either using Delete operator or Delete [ ] operator. New operator is used for dynamic memory allocation which puts variables on heap memory.
delete is used for one single pointer and delete[] is used for deleting an array through a pointer.
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.
Section 16.14 of the C++ FAQ lite answers this:
There are two popular techniques that do this. Both these techniques are in use by commercial-grade compilers, both have tradeoffs, and neither is perfect. These techniques are:
* Over-allocate the array and put n just to the left of the first Fred object. * Use an associative array with p as the key and n as the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With