Size of array (new[])

前端 未结 4 1420
挽巷
挽巷 2021-01-21 19:17

In debug heap I can get size of array, which was created by new[]:

int size = *((int *)((char *)ptr - 16));

It is working correctl

4条回答
  •  情歌与酒
    2021-01-21 20:21

    You are relying on an implementation detail. That's how your particular implementation stores the size of the memory region where the array is placed. As you already see, the size of the memory region may be bigger than the size of the allocated array.

    If you need to know the size of an array allocated with new[], you'll have to keep that value around.

提交回复
热议问题