In debug heap I can get size of array, which was created by new[]
:
int size = *((int *)((char *)ptr - 16));
It is working correctl
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 ...
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.
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:
new[]
and keep the size around for later usestd::vector
and get the size using std::vector::size
std::array
. Note that this option does not allocate memory on the heap (unless of course you new
the std::array
itself)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.