get size of malloc'd object

Spencer W. Thomas thomas at utah-gr.UUCP
Fri Jun 13 23:21:33 AEST 1986


In article <165 at daisy.UUCP> misha at daisy.UUCP (Mike Umansky) writes:
>	I have a need in my application to find the size of a
>	previously malloc'd object (maybe an array or structure).

We had this same need, and for many years satisfied it by writing a
macro SIZE(ptr) that `knew' how malloc saved the block size (usually in
the word preceding ptr).  Finally, with the 4.3 release, and in the
interests of easier portability (we were distributing our own malloc
with our code), we went to a different scheme:  We now do storage
allocation via two routines `new' and `dispose'.  The function `new'
asks malloc for the size requested plus one word, puts the size in the
extra word, and returns a pointer to the next word (obviously, it has to
worry about alignment, too, so it may not be quite this simple). The
function `dispose' readjusts the pointer passed to it and calls free.  A
third routine, `size', can then easily look at the word preceding the
pointer passed to it and return the size of the block.  This scheme has
the advantage of being blissfully independent of the underlying storage
allocation management.

-- 
=Spencer   ({ihnp4,decvax}!utah-cs!thomas, thomas at utah-cs.ARPA)



More information about the Comp.unix mailing list