Finding the size of a dynamic block of memory, only given the pointer
Recently a friend asked me was it possible to find the size of a block
of dynamically allocated memory with only the pointer available to
you.
After a bit of hacking I came up with this:
// ---------------------------------------------------------------
#include <iostream>
using std::cout;
using std::endl;
class Test
{
public:
Test() {}
void setValue (int elem, int value)
{
if (elem < 0 || elem > 100)
cout << "error outside bounds of array" << endl;
else
x[elem] = value;
}
private:
int x[100];
};
int main()
{
Test *t = new Test[42];
int *j = reinterpret_cast<int*>(t);
// Move back 16 bytes
j -= 4;
cout << "Value at 16 bytes to the left of entry to block is: " << *j
<< endl;
cout << "Number of elements in block pointed to by t of type
Test: " << *j / sizeof Test << endl;
return 0;
}
//
-----------------------------------------------------------------------
This code will work on vc6 and vc2005 express, and the value of (*j /
sizeof(Test)) will be 42, so that visual c++ stores the size of a
block at the start of a 16 byte boundary before the block of memory
starts.
I've looked through the C++ Standard and I can't find anything that
says about where the size has to be stored, so I'm assuming its
compiler implementation dependent. I've seen sort of similar behavour
on gcc 4.1 as well.
I'm just wondering if anyone has every come across this before and if
its platform independent in anyway??