Re: type punning question...
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Thu, 14 Sep 2006 22:07:07 GMT
"Douglas A. Gwyn" <DAGwyn@xxxxxxxx> writes:
"Jeff W. Boote" wrote:
Most implementations of the functions that take 'struct sockaddr *'
as an argument internally alias that memory using 'struct
sockaddr_in *' or 'struct sockaddr_in6 *' eventually.
There is a lot of historical cruft in the sockets interface,
and much existing code confutes AF_* with IF_* and has other
technical infelicities.
What C guarantees is that you can pun a pointer to one structure
type to that of another structure type, and use the result to
access any of the initial set of structure members that have
the same type according to both structure declarations. I leave
it to you to verify whether or not the posted example followed
this rule.
In other cases, use of a union type is suggested.
Where is that guaranteed?
C99 6.5.2.3p5 says:
One special guarantee is made in order to simplify the use of
unions: if a union contains several structures that share a common
initial sequence (see below), and if the union object currently
contains one of these structures, it is permitted to inspect the
common initial part of any of them anywhere that a declaration of
the complete type of the union is visible. Two structures share a
_common initial sequence_ if corresponding members have compatible
types (and, for bit-fields, the same widths) for a sequence of one
or more initial members.
Strictly speaking, this guarantee applies only if the two structures
are members of a union.
Of course the simplest way to satisfy the requirement is to lay out
the structures in the same way whether they're part of a union or not,
but at least in theory the common initial sequences of two structures
could be laid out incompatibly if the compiler can provide that
they're never used as members of the same union.
If it were intended to allow pointer punning as you describe, why
doesn't the standard say so?
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- References:
- type punning question...
- From: Jeff W. Boote
- Re: type punning question...
- From: Douglas A. Gwyn
- type punning question...
- Prev by Date: Re: Pointer equality and dereferencing
- Next by Date: Re: type punning question...
- Previous by thread: Re: type punning question...
- Next by thread: Re: type punning question...
- Index(es):
Relevant Pages
|
Loading