get size of malloc'd object

J. Eric Roskos jer at peora.UUCP
Thu Jun 19 05:19:48 AEST 1986


> Sure it is.  Just write your own routine to call malloc; allocate a
> sizeof(int) worth of extra space, then store the size of the thing you
> malloc'ed in the int at the front of the allocated block, advance the
> pointer past the place where your stored the size, and return that as
> the pointer to the block you allocated.  The size of the object is then
> found in the word preceeding the location pointed to by the object pointer.

hansen at pegasus points out that for this to work, the distance you advance
the pointer by has to be sufficient to put the pointer on the boundary
malloc usually aligns on.  So you have to allocate sizeof(ALIGN) extra
space for it to work for all possible types of data, where ALIGN is the
largest alignment boundary required for the machine.  E.g., on a typical
machine it might work for chars and ints, but not double-precision
floating point numbers.
-- 
E. Roskos

    "Hold on, Figment."
    "Why?"
    "The Idea Bag is full."
    "Then, let's imagine--"
    "--No, wait."
	    -- Dialogue from "Journey Into Imagination,"
	       Kodak exhibit, Epcot Center, Orlando, FL.



More information about the Comp.unix mailing list