How to find how much space is allocated by a call to malloc()?

限于喜欢 提交于 2019-12-29 07:35:09

问题


I'm trying to write a size function like this:

size(void *p,int size);

Which would return the size of an array which is pointed to by p. For example:

Int *a = malloc((sizeof(int)*100));
size(a,sizeof(int)); // this should return 100

I think this is possible because if I recall, malloc keeps track of the space allocated in some header bytes.

Here's what I have so far:

int size(void *p, int size)
{
  p = (unsigned int *)p - 1;
  unsigned int elements = (*(unsigned int *)p);
  return elements/size;
}

Now, assuming that the size of the space allocated is in the 4 bytes before the pointer, this should return the bytes, or offset. This is where I'm a bit in the dark. I can't figure out the specifics of how malloc formats these header bytes. How does malloc pack the header bits?

Thanks, I appreciate this. I'm sure there are things wrong with this code and it's not particularly portable and may be very system dependent, but I'm doing it for fun.


回答1:


If you like to peek and poke around beyond the memory your malloc() returns I recommend obtaining the source code of your allocator. This will be faster and safer than experimenting. ;-)




回答2:


In Visual Studio you can use _msize().




回答3:


I think you're relying on some implementation-specific malloc() behaviour. The implementation of malloc() is system-specific and the specification mentions very little about how this is performed.




回答4:


There's no portable way to do this. As others have said, either look at your allocator's code if you're doing a one-off program just poking around, or for some libraries (MS) there are extensions like _msize. malloc is allowed to do what it wants inside the allocator to track stuff, and there's no "safe" or standard-compliant way of getting that data.

If you really need this capability reliably in a real application, you'll have to build a shim around malloc/free that keeps a table of allocation sizes.




回答5:


You may find the glibc malloc-related functions to be of use. In particular you can call mallinfo() to get heap information. Some systems also define malloc_size, which is the BSD equivalent of _msize.




回答6:


If you really want to go that route, dlmalloc (the malloc used on glibc and uClibc among others) has some docs at http://g.oswego.edu/dl/html/malloc.html. Also, googling for how to exploit heap overflows will probably get you details for every platform out there, including ones without source code available.




回答7:


It's not in the standard. But there are platform-specific functions to do this, like _msize or malloc_usable_size.



来源:https://stackoverflow.com/questions/3886539/how-to-find-how-much-space-is-allocated-by-a-call-to-malloc

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