Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 511
kodai Avatar asked Oct 07 '10 23:10

kodai


People also ask

How much memory is allocated by malloc?

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.

How do I know my size after malloc?

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.

How can you determine the size of an allocated portion of memory?

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.

How can you tell the size of memory allocated by malloc using pointers?

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.


1 Answers

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

like image 143
Peter G. Avatar answered Sep 28 '22 02:09

Peter G.