Cast alignment warnings

Russ Allbery rra at stanford.edu
Mon Aug 1 20:28:42 UTC 2011


Julien ÉLIE <julien at trigofacile.com> writes:

> After having googled a bit, consecutively to Alexander's and your answer,
> I found out:
>     http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=340384

> Shouldn't sockaddr_storage be used instead of sockaddr as described in
> this bug on sparc64?

sockaddr_storage is specifically for use when you're allocating storage
for an arbitrary address.  It's not intended for use as a parameter to a
function; for that, the socket API says that you use a sockaddr and then
cast it based on the type field.  Note that even the new IPv6 API that
added the concept of sockaddr_storage actually passes things around as
sockaddrs (in, say, the addrinfo struct).

> Isn't alignment a real bug here?

No, or at least not obviously discernably from those warnings.

Alignment of structures matters *only* when you allocate storage for them,
and specifically when you allocate storage off the stack for them (since
in practice malloc always returns memory aligned with the tightest
requirement that could be enforced by that platform for the amount of
memory that you allocated, since it has no idea what you're going to put
in the memory).

The functions that gcc is complaining about aren't allocating storage.
They're taking in sockaddrs that were allocated somewhere else and casting
them to the more specific structs.  At that point, gcc has no idea whether
the struct passed in was aligned properly to be a sockaddr_in or not,
since it's looking at the function in isolation and just seeing that it
takes a sockaddr as an argument.  So basically it always warns about all
non-obfuscated uses of sockaddr other than just passing it to another
function.  Since it's basically impossible to avoid using sockaddrs when
writing C networking code due to functions like getpeername, the warning
is basically worthless, at least when the cast that it's warning about is
a cast of a sockaddr.

-- 
Russ Allbery (rra at stanford.edu)             <http://www.eyrie.org/~eagle/>



More information about the inn-workers mailing list