Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...