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

How can I get by pointing to a memory block allocated with malloc the size of it?

For instance:

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

I want to do this for debugging purposes.

+4
source share
4 answers

In Visual C ++, you can use _msize() to do this.

+7
source

Microsoft CRT has a function size_t _msize(void *memblock); which will give you the size of the selected block. Note that this can be (and actually probably will be) larger than the given size, due to the way the heap manager manages the memory.

This is a specific implementation, as mentioned in other answers.

+3
source

You can get dimensions only if you know how this is implemented, since it is implementation specific. I had to track the memory and write my own wrappers, as in this question . So, as David Heffernan says, you must remember the size I had to make in wrappers

0
source

There is no general (standardized) way to do this, since the malloc implementation is a specific system and architecture. The only guaranteed behavior is that malloc(N) will return at least N bytes or NULL. malloc always allocates more memory than specified - to store the required size (N) and, as a rule, some additional accounting data.

Windows / Visual C ++ Specification:

Additional data is stored in the memory segment until the address malloc returns to.

If p = malloc(N) and p != 0 , you can use the following code to determine the size of the requested memory, if you only know p :

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

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

Note that ulAllocSize not the size of the entire block allocated with malloc , but only the value passed as its argument is N

0
source

Source: https://habr.com/ru/post/1339156/


All Articles