get size of malloc'd object

jer at peora.UUCP jer at peora.UUCP
Mon Jun 23 23:21:07 AEST 1986


> 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.

That's a good point.  It's unfortunate that in all the system-specific
#defines that one can include, there isn't one that specifies the alignment
to be used in malloc's, etc; malloc has it #defined in it, as do a number
of other programs (e.g., Peter Honeyman's "pathalias" program).

Personally I still favor putting the size up at the front, eventhough it
requires now making the alignment a configuration parameter (i.e., the user
has to specify it for various machines), because maintaining a linked list
or other external record of the size introduces a consistency problem -- you
have to keep your external size information consistent with what malloc
knows the size to be, i.e., the physical separation of the allocated block
and the array or linked list that maintains the information makes it more
likely that they can become inconsistent.

(Notice, incidentally, that this is essentially a flaw in C -- there is an
essential piece of information, the alignment constant, that is not
available from within the language, eventhough the language allows one
to do things that require this information.)

Actually there's a trick you could use to get the alignment constant, maybe,
however:

	char *p, *q;
	int diff;

	p = malloc(1);
	q = malloc(1);

	diff = q - p;
	if (diff < 0) diff = p - q;

But it's not really portable either.  Although the argument to malloc is
defined to be a number of "bytes", and although in C a "byte" is an
"unspecified unit ... which is the same size as a char" (K&R p. 126), and
subtracting two pointers gives "the number of elements between p and q"
(K&R p. 98), where in this case an "element" is a char which is the same
size as a "byte", which means the distance computation itself is correct,
you're not guaranteed that the two consecutive mallocs will give
consecutive blocks of memory -- they certainly won't be likely to after
some other mallocs and frees have been done.  It's hard to see a situation
where the initial allocations wouldn't be consecutive, but it's not
guaranteed, and that's sufficient reason to have doubts.  (The reason for
the "if" above is to handle mallocs that allocate consecutively upwards
or downwards; both of which, like stacks that grow upwards or downwards,
do exist.)

Of course, our "compiler wizard" who is sitting here in my office reading
the newspaper says "just align it on a quadword".  :-)
-- 
E. Roskos



More information about the Comp.unix mailing list