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.
The malloc() function reserves a block of storage of size bytes. Unlike the calloc() function, malloc() does not initialize all elements to 0. The maximum size for a non-teraspace malloc() is 16711568 bytes.
To determine the size of data elements to be reserved by calloc or malloc in a machine-independent way, the sizeof operator should be used. The sizeof operator returns the size of the specified item in bytes.
Q) How can you determine the size of an allocated portion of memory? In C language, we can calculate the size of the static array using the sizeof operator but there is no operator to calculate the size of the dynamically allocated memory.
ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.
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. ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With