如何找到多少空间是通过调用分配到的malloc()? [英] How to find how much space is allocated by a call to malloc()?

查看:148
本文介绍了如何找到多少空间是通过调用分配到的malloc()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个函数的大小是这样的:

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

size(void *p,int size);

这将返回这是由p指向数组的大小。例如:

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

我认为这是可能的,因为如果我还记得,malloc的跟踪一些头字节分配的空间。

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;
}

现在,假设分配的空间的大小是在指针之前的4个字节,这应返回的字节数,或偏移。这是我在黑暗中的一点。我想不通的malloc的如何格式化这些头字节的具体细节。如何收拾的malloc头位?

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?

谢谢,我AP preciate这一点。我敢肯定有事情不对的code和它并不特别是便携式,可能是非常依赖于系统,但我这样做是为了乐趣。

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.

推荐答案

如果你喜欢窥视闲逛超出了你的内存的malloc()返回时,我建议你获得的分配器源$ C ​​$ C。这将是比试验更快,更安全。 ; - )

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. ;-)

这篇关于如何找到多少空间是通过调用分配到的malloc()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆