get size of malloc'd object

brett at wjvax.UUCP brett at wjvax.UUCP
Sat Jun 21 01:19:25 AEST 1986


In article <2206 at peora.UUCP> jer at peora.UUCP (J. Eric Roskos) writes:
>
>	It is really hard to come up which general purpose algorithmic 
>	solutions to problems without having even a glimmer of what
>	environment you are talking about ...
>
>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.
>
>Also provide a routine to deallocate the block by backing the pointer up
>before calling free().
>
>This approach is portable, simple, and easy to understand.
>Also it doesn't require any assumptions about what kind of objects are
>being allocated.

In fact, this assumes that the resulting pointer

	(malloc(len+sizeof(int))+sizeof(int))

is still well-aligned.  This is only true if sizeof(int) is the most coarse
alignment boundary on the machine.  If, for example, structures require more
coarse alignment, attempting to cast the above pointer to a structure pointer
will fail.

-------------
Brett Galloway
{pesnta,twg,ios,qubix,turtlevax,tymix,vecpyr,certes,isi}!wjvax!brett



More information about the Comp.unix mailing list