Looking at C ++ new [] cookie. How portable is this code?
I came up with this as a quick fix to a debugging problem - I have a pointer variable and its type, I know it points to an array of heap allocated objects, but I don't know how many. So I wrote this function to look at the cookie that stores the number of bytes when the memory is allocated on the heap.
template< typename T >
int num_allocated_items( T *p )
{
return *((int*)p-4)/sizeof(T);
}
//test
#include <iostream>
int main( int argc, char *argv[] )
{
using std::cout; using std::endl;
typedef long double testtype;
testtype *p = new testtype[ 45 ];
//prints 45
std::cout<<"num allocated = "<<num_allocated_items<testtype>(p)<<std::endl;
delete[] p;
return 0;
}
I would like to know how portable this code is.
+2
a source to share
3 answers
You can globally overload new / delete operators in the array and put the size in the memory area. You get a portable solution.
The code below shows how:
void * operator new [] (size_t size)
{
void* p = malloc(size+sizeof(int));
*(int*)p = size;
return (void*)((int*)p+1);
}
void operator delete [] (void * p)
{
p = (void*)((int*)p-1);
free(p);
}
template<typename T>
int get_array_size(T* p)
{
return *((int*)p-1)/sizeof(T);
}
int main(int argc, char* argv[])
{
int* a = new int[200];
printf("size of a is %d.\n", get_array_size(a));
delete[] a;
return 0;
}
Result:
size of a is 200.
+2
a source to share