Is there a way to get the size of previously allocated memory on a heap?
For example:
//pseudo-code
void* p = operator new (sizeof(int) * 3);
unsigned size = getSomeHow(p);
Is there a way to get the size of previously allocated memory on a heap?
For example:
//pseudo-code
void* p = operator new (sizeof(int) * 3);
unsigned size = getSomeHow(p);
You can't do it at all times, since operator new()
can be overloaded in any reasonable way and maybe even without using the runtime heap.
In case operator new()
is implemented with malloc()
in Visual C++ you can use _msize()
.
Although Sharptooth is right in his answer (new can be overloaded), the solution might be just in this fact. By overloading new, you can easily add your own implementation of new and delete. In your implementation of new you should:
The delete operator should do the opposite:
If you do it this way, make sure to implement all flavours of new and delete (throwing and non-throwing, new and new[], delete and delete[], ...).
Also be careful with 3rd party libraries. They sometimes put the call to new in their compiled code in their DLL, but but the call to delete in the header. This means that new and delete will use different implementations and your application will crash.
EDIT:
The rounding to the multiple of 8 bytes and the addition of 8 bytes is needed because data should be stored at an addres that is a multiple of its size:
Since doubles are the largest native data type that I'm aware of, we round to a multiple of 8 bytes and we add 8 bytes to make sure that keep these requirements.
new
operator to call malloc()
and store the size in a global std::map<void*, size> alloc
. Then this getSomeHow()
function will behave like you want:
getSomeHow(void *p){
return alloc[p];
}