Size of array (new[])

前端 未结 4 1425
挽巷
挽巷 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条回答
  •  旧时难觅i
    2021-01-21 20:19

    As others have mentioned, you're using an implementation detail to figure out the size of the allocated array. You've managed to figure out that if you walk back 16 bytes from the beginning of the pointer returned by new[] you can get the size of the array.

    16 bytes of extra allocation seems excessive and this most likely will not be the case if you compile the release version of your application. The implementation is probably allocating some extra bytes before and after the length you've requested and filling it with magic values to help catch your code overrunning the bounds of the array. This extra space will probably not be allocated in the release version.

    Also, you yourself mention that if the array size is smaller than some threshold the 16 byte number does not seem valid anymore. It is possible that if you allocate bigger objects than whatever you're allocating right now, you'll have to walk back even further to get to the size.

    So, the solutions available to you are:

    • Continue allocating using new[] and keep the size around for later use
    • Use std::vector and get the size using std::vector::size
    • If know the size of the array beforehand, and don't need to resize it, use std::array. Note that this option does not allocate memory on the heap (unless of course you new the std::array itself)

提交回复
热议问题