I was wondering how delete[]
knows the size of a dynamically allocated array, and I found this question (and also this question on a Microsoft forum, but the answer is similar). Turns out the answer is
This is usually stored in a "head" segment just before the memory that you get allocated.
Thus the exact details are implementation specific.
Under that answer one of the comments asks why this quite useful piece of information is not available to the programmers, forcing us to pass around variables denoting the size. The answer the comment got is
Forcing the allocator to store the requested size (so that you wouldn't need to pass the array size yourself) might be a small encumbrance, but it could have performance impacts on conceivable allocator designs
To me, that isn't very convincing considering the size should be accessible to delete[]
anyhow.
My question: is it possible (for a programmer) to retrieve the size somehow?
I am aware that there's a Microsoft special way (as it was noted in the aforementioned MS forum), but I am after something standardized.
You can use the Microsoft-specific function _msize() to get the size of a dynamically allocated array from the pointer, even when it is passed to another function than the one which did the allocation.