3 ms·
The memory layout of a C struct is ABI and compiler dependent. Some compilers conform to same ABI in same system or similar system and work almost exactly the
by nabla9 7y ago
The memory layout of a C struct is ABI and compiler dependent.
Some compilers conform to same ABI in same system or similar system and work almost exactly the same, so you may grow old thinking that's how it is until it's too late. I think gcc, clang and Intel work almost the same in Linux and OSX.
- doublement 7y agoIndeed, that's why I specified putting the members of the C structure on the wire, not the structure as a whole, so it's just basic types in network byte order (i.e. consistent endian-ness) being sent.
- itronitron 7y agoI've worked on an application where that was the standard data transfer scheme, and then while working with protobuf on another project felt that after looking under protobuf's covers it was doing something very similar but wrapping an entire API around it.
- CoolGuySteve 7y agoNo, not really. #pragma pack and/or __attribute__((packed)) have been supported for eons now and guarantee the alignment of struct members between compilers. In newer C++ specs, you can also static assert that the struct is a POD type to statically ensure that there's no accidental vtable pointer. This argument pops up every time someone mentions this and every time it's completely uninformed.
- cyphar 7y agoThough it should be noted that packed structures cause compilers to produce absolutely garbage code when accessing them (because most of the accesses become unaligned) and it becomes incredibly memory-unsafe (as in "your program may crash or corrupt memory") to take pointers of fields inside the struct because they are (usually) presumed to be aligned by the compiler. Explicit alignment doesn't suffer from this problem nearly as badly (yeah, you might have to add some padding but that's hardly the end of the world -- and if you have explicit padding fields you can reuse them in the future).