Size of array (new[])

前端 未结 4 1421
挽巷
挽巷 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:17

    Like this:

    std::vector< int > array( 1024 ); // allocate 1024 element array.
    int size = array.size();
    int sizeInBytes = size * sizeof( int );
    

    ;)

    It really is the best way what you are trying to do is take adavantage of something which is COMPLETELY compiler/library dependent ... Its a really bad thing to do, in general, as your code becomes completely unportable not even mentioning that the next version of your compiler may come with a different memory allocation implementation which breaks what you are trying to do ...

    0 讨论(0)
  • 2021-01-21 20:17

    Any way that involves mining something from the CRT is undefined and cannot work 100%.
    Your only way is to override operator new[] that will store the size somewhere defined, like allocating bigger object with size prefix.

    0 讨论(0)
  • 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)
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题