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.
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. 😉