Finding size of dynamically allocated array

前端 未结 7 597
礼貌的吻别
礼貌的吻别 2020-12-10 11:08

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

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 11:36

    The runtime must deallocate the same amount as it allocated, and it does keep track of this in some manner (usually very indirectly). But there's no reliable way of getting from amount allocated to number of elements: the amount allocated cannot be less than the number of elements times the size of each element, but it will often be more. Alignment considerations, for example, mean that new char[5] and new char[8] will often allocate the same amount of memory, and there are various allocation strategies which can cause significantly more memory to be allocated that what is strictly necessary.

提交回复
热议问题