Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the size of a dynamicly allocated array the way `delete[]` does?

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.

like image 349
Ayxan Haqverdili Avatar asked Oct 16 '25 13:10

Ayxan Haqverdili


2 Answers

If you work with open source libraries, then yes you can! Just look up the source, figure out how and go for it.

It is still a bad idea though, since there are no guarantees: the implementation could change at any moment and is not guaranteed to be portable even between Unix and Linux. The number could also be too large, since it might be advantagous to allocate more, for example to align. It is also unnecessary: when you new a space you know the size. You could just pass it, or store it in some place which you control. This is not worse than looking it up trough the implementation of malloc.

like image 141
Cheiron Avatar answered Oct 18 '25 01:10

Cheiron


My conclusion is:
The size of the array might be stored in memory, but it is not necessarily the case; there are other ways of achieving the desired behavior, each with its own trade-offs and ISO specifically gives the compiler writers the freedom to choose so that they can optimize it as much as necessary.
That is to say, there is not a single, standardized way of getting the size of a dynamically allocated array as of now.

like image 36
Ayxan Haqverdili Avatar answered Oct 18 '25 03:10

Ayxan Haqverdili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!