Help me cast this!

Henry Spencer henry at utzoo.uucp
Sat May 7 02:52:21 AEST 1988


>     I have been wondering why malloc() returns a (char *), when
> it is guaranteed to satisfy all alignment requirements. It
> would seem to be more proper to return (maxalign *), where
> maxalign is a type with the strictest alignment requirements of
> all types. This would inform lint that the cast is safe.

If you accept the need to cast all results of malloc, there is nothing
inherently very wrong with this.  Note, however, that the type of maxalign
is implementation-dependent.  On some systems I'm not sure, actually, that
there is a specific type that expresses the maximal alignment constraint.
(Since I carefully avoid these silly machines that have segments, I'm not
intimate with the details of their flaws.)

> ...redefined as void *malloc(). Is a (void *) guaranteed to
> satisfy all alignment requirements?

No.  A "void *" is guaranteed to be able to hold any other pointer intact.
(Well, any other data pointer.)  This means that it has pretty much the
same characteristics as "char *", and in fact I think it is required to
use the same representation.  The purpose of "void *" is to be a real, true
pointer-to-anything, so that "char *" can go back to being specifically
pointer-to-char.  The properties of "void *" are also defined in such a way
that many conversions between it and other pointer representations do not
require explicit casts.

There is still no fully portable way to say "maximally aligned pointer".
If somebody wants to implement one and try it out, the next incarnation of
X3J11 would probably be interested in hearing about it when the time comes
to revise the C standard, several years from now.  I don't think there is
any actual implementation experience to justify trying to put it in now.
I'm not even quite sure how I would add this to the language:  one wants
something that shares "void *"'s property of not needing explicit casts,
while also being maximally aligned (which may not be expressible as an
ordinary C type).  Perhaps "struct *"?  (Ugh.)
-- 
NASA is to spaceflight as            |  Henry Spencer @ U of Toronto Zoology
the Post Office is to mail.          | {ihnp4,decvax,uunet!mnetor}!utzoo!henry



More information about the Comp.lang.c mailing list