Click to See Complete Forum and Search --> : On allocation from the heap


Sayan Mukherjee
December 26th, 2002, 05:39 AM
Hi,

When we allocate memory from the heap using malloc(), calloc()
or new, we get a valid pointer to the allocated memory.

Given this pointer, is it possible to get the number of bytes allocated?

Thanks in advance.

j0nas
December 26th, 2002, 08:28 AM
There are no standard ways of doing this. Some compilers let you access the internal heap data structure, via some functions, to find out certain stuff, like mem block size etc. In VC6 and VC7, you can use _msize (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/HTML/_crt__msize.asp) on a block of memory to find out the size of that block. It is not portable code--I would normally not use that way... but you may have good reasons for it. Hope it helps.

kuphryn
December 26th, 2002, 12:37 PM
One solution is to determine the size of the object you cast the pointer to. In other words, the size of the allocation depends on the object you cast. Consider sizeof().

Kuphryn

Andreas Masur
December 26th, 2002, 12:46 PM
Originally posted by kuphryn
One solution is to determine the size of the object you cast the pointer to. In other words, the size of the allocation depends on the object you cast. Consider sizeof().

Kuphryn
'sizeof()' does not work with dynamically allocated memory...it would return the size of the pointer which is always the same (e.g. 4 bytes on a windows system)...

kuphryn
December 26th, 2002, 01:26 PM
Correct. I mentioned the object, not the pointer to it.

Kuphryn

cup
December 27th, 2002, 03:31 AM
You could always write your own version - say allocate.

void* allocate (int bytes)
{
int* result = (int*) malloc (sizeof (bytes) + bytes);
*result = bytes;
return (void*)(result + 1);
}

int allocateSize (void* whatever)
{
int* sizeinfo = (int*) whatever;
sizeinfo--;
return *sizeinfo;
}

You'll have to do similar fiddles for free, calloc and realloc.

DrPizza
December 30th, 2002, 05:24 AM
Alignment be damned, eh?

Don't do that. It's non-portable (not to mention horribly written -- in C, don't cast the return value of malloc(); in C++ don't use malloc()), because you potentially foul up the alignment of the memory. As such, it's a trick that implementations can do, but users cannot.

You'll have to store the information in a separate data structure to do this safely.