Jarx
Jarx

Reputation: 63

Visual Studio 2010 C++: Get size of memory block allocated by malloc

How can I get, given a pointer to a block of memory allocated with malloc, the size of it?

For example:

void* ptr = malloc( 10 ); //Allocate 10 bytes
printf( "%d", GetMemSize( ptr ) ); //Should print 10

I want to do this for debugging purposes.

Upvotes: 6

Views: 3049

Answers (4)

sharptooth
sharptooth

Reputation: 170519

In Visual C++ you can use _msize() for that.

Upvotes: 9

Bojan Komazec
Bojan Komazec

Reputation: 9536

There is no general (standardised) way of doing this as implementation of malloc is system and architecture specific. The only guaranteed behaviour is that malloc(N) will return at least N bytes or NULL. malloc always allocates more memory than asked - to store the size that was asked for (N), and usually some additional bookkeeping data.

Windows / Visual C++ specific:

Additional data is stored in memory segment before the one which address is returned by malloc.

If p = malloc(N) and p != 0 you can use following code to determine size of memory asked for if knowing only p:

Windows NT: unsigned long ulAllocSize = *((unsigned long*)p - 4);

Windows CE: unsigned long ulAllocSize = *((unsigned long*)p - 2);

Please note that ulAllocSize is not the size of entire block allocated with malloc but only the value passed as its argument - N.

Upvotes: 0

ymett
ymett

Reputation: 2454

The Microsoft CRT has a function size_t _msize(void *memblock); which will give you the size of the allocated block. Note this may be (and in fact is likely to be) larger than the size asked for, because of the way the heap manager manages memory.

This is implementation specific, as mentioned in other answers.

Upvotes: 3

dubnde
dubnde

Reputation: 4441

You can only get the sizes if you know the way it is implemented as it is implementation specific. I had to track the memory and had to write my own wrappers as in this question. So as David Heffernan says, you have to remember the size as I had to do in the wrappers

Upvotes: 0

Related Questions