Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding size of dynamically allocated array

Why is it not possible to get the length of a buffer allocated in this fashion.

AType * pArr = new AType[nVariable];

When the same array is deallocated

delete [] pArr;

the runtime must know how much to deallocate. Is there any means to access the length before deleting the array. If no, why no such API is provided that will fetch the length?

like image 856
Ram Avatar asked Sep 06 '25 07:09

Ram


2 Answers

Is there any means to access the length before deleting the array?

No. there is no way to determine that.
The standard does not require the implementation to remember and provide the specifics of the number of elements requested through new.
The implementation may simply insert specific bit patterns at end of allocated memory blocks instead of remembering the number of elements, and might simply lookup for the pattern while freeing the memory.
In short it is solely an imlpementation detail.


On a side note, There are 2 options to practically overcome this problem:

  1. You can simple use a std::vector which provides you member functions like size() or
  2. You can simply do the bookkeeping yourself.

new atleast allocates enough memory as much as you requested.
You already know how much memory you requested so you can calculate the length easily. You can find size of each item using sizeof.

Total memory requested / Memory required for 1 item = No of Items
like image 90
Alok Save Avatar answered Sep 10 '25 06:09

Alok Save


The runtime DOES know how much was allocated. However such details are compiler specific so you don't have any cross platform way to handle it.

If you would like the same functionality and be able to track the size you could use a std::vector as follows:

std::vector< AType > pArr( nVariable );

This has the added advantage of using RAII as well.

like image 20
Goz Avatar answered Sep 10 '25 05:09

Goz