A similar lint question (and questions about casts)

Doug Gwyn gwyn at smoke.BRL.MIL
Sat Dec 3 00:38:30 AEST 1988


In article <3737 at pt.cs.cmu.edu> dlc at dlc.fac.cs.cmu.edu (Daryl Clevenger) writes:
>	    struct sockaddr_in saddr;
>	    if (bind(s, (struct sockaddr *)&saddr, len) < 0) {
>Every time I lint this, I get "warning: illegal structure pointer combination"
>for the bind() call.  Here is the lint prototype from llib-lc:
>    int bind(s, n, l) struct sockaddr *n; { return 0; }
>    1) Given 2 structure pointers, is it portable to cast from one to
>       the other?  I remember a discussion a while back and I believe
>       that the consensus was that "struct <name> *" pointers must
>       "smell the same" or problems may result.

The conversion is always permitted, but use of the resulting pointer
is valid only if the original pointer was to an object suitably aligned.
Structure pointers all must have the same representation (this can be
deduced from other requirements), but not all structure types need be
aligned the same.  Thus "lint" is right to warn about this.  The ideal
solution here is to use a union of the two structure types, and pass
the address of the appropriate union member to the function.

>    2) ...

It is the object alignments that matter, not their sizes (K&R 1st Ed.
was not sufficiently precise).  In general you cannot deduce alignment
from size or vice versa.

>    3) Given pointer, p, obtained via legal coercion, is it safe, i.e.
>       no exception will be raised, to deference p if p is suitably aligned?

No, for example the size of the supposed object pointed to after the
conversion may exceed the size of the storage actually allocated.

There are portable uses of pointer conversion.  The general rule of
thumb is, if a pointer to a type really does point to an object of
that type, it may safely be dereferenced.  Otherwise it depends on
the specific circumstances.  Simply converting a pointer does not
in itself impose any sanity requirements on the resulting pointer.



More information about the Comp.lang.c mailing list