get size of malloc'd object

Tom Stockfisch tps at sdchem.UUCP
Thu Jun 19 09:08:33 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.
>...
>This approach is portable, simple, and easy to understand.
>Also it doesn't require any assumptions about what kind of objects are
>being allocated.
>-- 
>E. Roskos

This is NOT portable.  Suppose your machine requires "doubles" to be aligned on
addresses divisible by 8 and sizeof(int) == 4.  You do

	double	*dp =	(double *)my_malloc( (unsigned)100 * sizeof(double) );

If my_malloc() calls malloc() and then increments the
pointer returned by malloc by 4, you will get a segmentation fault as soon
as your allocated space is accessed.  A *portable* way to do this (which
wastes a little memory, but doesn't require that you know the worst-case
alignment size) is to hand both the unit size and number of units to
my_malloc() and allocate one extra *unit* to store the size of the space in.
Of course, if the unit size < sizeof(int) you have to do a little extra
diddling.

Usually when I need to know the end of the allocated space I need to access
it too often to be done by a subroutine call so I set up a structure to
replace the pointer:
	struct foo {
		arraytype	*beg;	/* begining of array */
		arraytype	*end;	/* end of array */
	}	bar;

-- Tom Stockfisch, UCSD Chemistry



More information about the Comp.unix mailing list