get size of malloc'd object

Doug Gwyn gwyn at brl-smoke.ARPA
Sun Jun 29 13:22:18 AEST 1986


In article <9895 at ucsfcgl.ucsfcgl.UUCP> arnold at ucsfcgl.UUCP (Ken Arnold%CGL) writes:
-In article <9894 at ucsfcgl.ucsfcgl.UUCP> I write:
->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.
-
-I don't know what came over me.  I only wish I could say that I was on
-drugs at the time I wrote this, since at least my embarassment could
-have been partially compensated by the entertainment.  Please forgive
-my obvious error, and just chalk it up to a long, tired day.

I dunno, Ken -- I thought the idea of putting the size at the end of
the data was pretty amusing.

It might be worth observing that several requests to these nets take
the general form:
	"How do I do X?  Here's what I tried so far..."
where "X" is only part of a solution to the REAL problem.  Usually,
there are other solutions to the REAL problem that do not have "X"
as a subcomponent.  It often happens that solving "X" is much harder
than solving the REAL problem.  So, if you find yourself having
difficulties like this, it may be that you've prematurely settled on
a difficult approach and that it might be worthwhile to step back
and consider whether there is some simpler, more straightforward
method.

Now, if you find yourself truly needing to keep track of the size of
dynamically-allocated chunks of data space, you can take either of
two good general approaches.  The first is:

	typedef struct
		{
		void	*loc;
		size_t	size;
		}	alloc_info;	/* this should be in a header file */

	alloc_info *
	my_alloc( size_t length )	/* use this instead of malloc */
		{
		extern void	free(void *), *malloc(size_t);
		register alloc_info	*p;

		if ( (p = (alloc_info *)malloc( sizeof(alloc_info) )) != 0
		  && (p->loc = malloc( p->size = length )) == 0
		   )	{
			free( (void *)p );
			p = 0;
			}
		return p;
		}

and the second is to supply one's own memory allocator (Knuth's
"boundary tag" method is particularly suitable for this application).
Make sure that your allocator can coexist with malloc(), since the C
library may have to invoke malloc().  One way to guarantee this is to
rip off a large pool of memory with malloc() early on, then have one's
own allocator restricted to allocating from this pool.  If you're more
ambitious, you could try implementing your own virtual memory scheme
using buffers into a disk file (this makes data access more complicated
than simply using pointers, however).  The best implementation I ever
had was under single-job RT-11, where I could directly manipulate the
KT-11 memory management hardware registers.  (Not feasible under UNIX,
but perhaps worth considering for stand-alone applications.)



More information about the Comp.unix mailing list