malloc question

Andy Lieberman andy at garnet.berkeley.edu
Thu Jun 15 08:08:42 AEST 1989


In article <25424 at agate.BERKELEY.EDU> I wrote:
>I want to write a function that will return the size of a memory
>block that was allocated with malloc.  How can I determine this
>knowing only the pointer to the start of the block? (I know I
>could keep track myself, but I don't see why I should have to.)
>I'm using SUNOS 3.5.  
>

Tony Olekshy (...!alberta!oha!tony or tony at oha.UUCP) replies:

This is not portable, but most malloc() keep the size of the block in
an int just before the block (ie, they allocate sizeof(int) more bytes
than you ask for, and return you a pointer sizeof(int) bytes into the
block).  So, if p is a char* from malloc, you can usually use something
like *(int *)(p - sizeof(int)).
-- 


David Elliott		dce at Solbourne.COM
			...!{boulder,nbires,sun}!stan!dce
replies:

It depends on what you mean by the size of the memory block.

If you want the size of the block that malloc gave you, you can
decode the data found before the block (malloc stores a "bucket number"
in the area before the block, and you do exponentiation on the number
to get the size of the blocks in that bucket).  This is highly unportable,
and Sun could easily change malloc in the future, so be forewarned.

If you want the size of the data you asked for, that isn't stored.  For
speed, malloc just gives you a pointer to a block of memory whose size
is usually the next power of 2 above the size you asked for (depending
on alignment and so forth).  So, if you need the size you asked for,
you'll need to write some code (or more likely someone will send you
the code since this topic has come up a couple of times before) to
do something like maintain a table of sizes for you.
-- 


I used Tony's method which seems to return a number four larger than what I
would expect (e.g., for a malloc(1024), Tony's function returns 1028).

Thanks for all the responses,
Andy Lieberman



More information about the Comp.unix.questions mailing list