R
Roy Hills
When I'm reading from or writing to a network socket, I want to use a
struct to represent the structured data, but must use an unsigned char
buffer for the call to sendto() or recvfrom().
I have two questions:
1. Is it generally safe to "overlay" the structure on the buffer,
e.g.:
unsigned char buffer[BUFSIZ];
struct header {
whatever;
};
struct header *hdr = (struct header *) buf;
or is it safer / more portable to declare a seperate struct and use
memcpy() to copy it to or from the buffer? Obviously, it would be
more efficient to avoid the memcpy() if possible.
The overlay seems to work fine, but I'm always concerned that I'm
doing something non-portable or ineligant whenever I cast a pointer.
I've seen both approaches used in practice.
2. How should I deal with alignment?
I've read that there's no guarantee that struct members will be
adjacent in memory because of alignment requirements. So in theory, I
shouldn't try to overlay or memcpy() a struct to or from a buffer at
all. However, just about every program I've seen seems to do this with
no ill effects or lack of portability.
Are there any general guidelines on when I'm likely to run into struct
alignment padding? Is it normally safe if elements are aligned
according to size, e.g. a 32-bit on an address divisible by 4 and a
16-bit on an address divisible by 2? Is it safe to assume that there
will be no padding at the beginning of the struct? (i.e. the compiler
will automatically position the first element with the requireed
alignment?).
Roy Hills
struct to represent the structured data, but must use an unsigned char
buffer for the call to sendto() or recvfrom().
I have two questions:
1. Is it generally safe to "overlay" the structure on the buffer,
e.g.:
unsigned char buffer[BUFSIZ];
struct header {
whatever;
};
struct header *hdr = (struct header *) buf;
or is it safer / more portable to declare a seperate struct and use
memcpy() to copy it to or from the buffer? Obviously, it would be
more efficient to avoid the memcpy() if possible.
The overlay seems to work fine, but I'm always concerned that I'm
doing something non-portable or ineligant whenever I cast a pointer.
I've seen both approaches used in practice.
2. How should I deal with alignment?
I've read that there's no guarantee that struct members will be
adjacent in memory because of alignment requirements. So in theory, I
shouldn't try to overlay or memcpy() a struct to or from a buffer at
all. However, just about every program I've seen seems to do this with
no ill effects or lack of portability.
Are there any general guidelines on when I'm likely to run into struct
alignment padding? Is it normally safe if elements are aligned
according to size, e.g. a 32-bit on an address divisible by 4 and a
16-bit on an address divisible by 2? Is it safe to assume that there
will be no padding at the beginning of the struct? (i.e. the compiler
will automatically position the first element with the requireed
alignment?).
Roy Hills