How is is that it is possible for us to delete dynamically allocated arrays, but we can't find out how many elements they have? Can't we just divide the size of the memory location by the size of each object?
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.
You can just use free to delete a dynamically allocated array. int* array = malloc(10*sizeof(int)); ... free(array); If you allocated memory for each array element, you'll also need to free each element first.
Deleting array elements When the delete operator removes an array element, that element is no longer in the array.
Usually operator new allocates a memory block with some invisible for the user header that contains the size of the allocated block. free the memory, the de-allocator knows exactly how much memory to free. The delete operator just randomly selects memory cells for erasure.
In C++, both...
...are implementation details that the Standard doesn't require be made available programatically, even though the memory allocation library must remember the former and the compiler the latter so it can invoke the destructor on the correct number of elements.
Sometimes the compiler may see there's a constant-sized allocation and be able to associate it reliably with the corresponding deallocation, so it could generate code customised for these compile-time-known values (e.g. inlining and loop unrolling), but in complex usage (and when handling external inputs) a compiler may need to store and retrieve the # elements at run-time: enough space for the #element counter might be put - for example - immediately before or after the address returned for the array content, with delete[] knowing about this convention. In practice, a compiler may choose to always handle this at run-time just for the simplicity that comes with consistency. Other run-time possibilities exist: e.g. the # elements might be derivable from some insight into the specific memory pool from which the allocation was satisfied combined with the object size.
The Standard doesn't provide programmatic access to ensure implementations are unfettered in the optimisations (in speed and/or space) they may use.
(The size of the memory location may be greater than the exact size required for the requested number of elements - that size is remembered by the memory allocation library, which may be a black-box library independent of the C++ compiler).
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