malloc()

KW Heuer kwh at bentley.UUCP
Tue May 20 01:29:49 AEST 1986


In article <3674 at sun.uucp> sun!guy writes:
[bentley!kwh writes:]
>> I saw the need for a "ALIGN *" datatype, and was hoping "void *" would
>> be it.  (Nope, just a useless synonym for "char *").  The idea would
>> be that, just as it's always legal to cast any pointer into a "char *",
>> it would be legal to cast *from* "ALIGN *" to any pointer.  Then lint
>> would shut up about malloc()!
>
>No, you just don't understand how it works.  From the August 11, 1985 C
>standard draft:
>
>	C.2.2.3 Pointers
>
>	   A pointer to "void" may be converted to a pointer to an
>	object of any type.  A pointer to an object of any type may be
>	converted to a pointer to "void" or to a pointer to an object
>	of less strict alignment and back again without change.
>
>Nowhere is it implied that "void *" is a synonym for "char *".

Since sizeof(char) == 1 (I believe that's now a guaranteed rule rather than
merely "true in all known implementations", right?), it has the least strict
alignment.  Thus your last quoted sentence implies that "char *" can also
hold a pointer of any type, and restore it unchanged.  And to even attempt
to restore it means that "char *" must meet the first property as well.  So,
although not necessarily synonyms, they do have the same properties, except
that "char *" conversions usually require a cast to be acceptable.

>No, the language does not *guarantee* that a "void *" is properly aligned,
>but there's no way for it to do so anyway.  Big deal.  The language couldn't
>*guarantee* that an "ALIGN *" is properly aligned either...

What I had in mind was that "ALIGN *" would be a synonym for "int *" or
whatever happens to be the most restrictive pointer type.  The "guarantee"
would be as good as the "guarantee" on an "int *".

>> Also, having malloc() return a real "ALIGN *" would be convenient for word-
>> addressible machines where "char *" requires extra bits.
>
>Maybe, but I'm not sure the added convenience of having "malloc" be able to
>return a value of a type requiring fewer bits is sufficient to justify
>adding another type to the language.

Well, what *is* the justification for adding "void *" to the language?  To
allow people to shove pointers around without casts?  (Shudder!)  To make
lint shut up about malloc()?  Or just to distinguish "generic pointers" from
pointers that can be dereferenced?  (Could be done with a typedef.  So could
"void", but they put it in anyway.)

I do not strongly object to the addition of "void *", but I am worried about
it "hiding" errors.  (I'm one of those purists who thinks that programmers
*should* use casts to change types.)  Also, it's a misnomer; it has nothing
to do with "void".

Karl W. Z. Heuer (ihnp4!bentley!kwh), The Walking Lint



More information about the Comp.lang.c mailing list