get size of malloc'd object

Ken Arnold%CGL arnold at ucsfcgl.UUCP
Wed Jun 25 09:54:58 AEST 1986


In article <2081 at umcp-cs.UUCP> chris at umcp-cs.UUCP (Chris Torek) writes:
>In article <2206 at peora.UUCP>, jer at peora.UUCP (J. Eric Roskos) writes:
>>... 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.
>>
>
>Unfortunately, it is not necessarily portable.  I can imagine a
>machine where `double' arguments must be aligned on an eight-byte
>boundary, but integers are only four bytes wide.  In this case
>calling the new routine to allocate doubles would result in an
>odd-address-style trap when the returned value is used.

So put the int at the end of the space, after increasing the size
to be allocated by sizeof (int) + enough space to align the int
on a byte which is a multiple of sizeof (int).  Then return the
original malloc()ed pointer.

Can we say "hack"?

		Ken Arnold



More information about the Comp.unix mailing list