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

扶醉桌前 提交于 2021-01-27 05:43:48

问题


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.


回答1:


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




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/4955399/visual-studio-2010-c-get-size-of-memory-block-allocated-by-malloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!