3 ms·
Pack your structs to not have padding? The probable reason it sometimes works is purely how the compiler decides to do the copy. Anything that relies on implici
by nwmcsween 6y ago
Pack your structs to not have padding? The probable reason it sometimes works is purely how the compiler decides to do the copy. Anything that relies on implicit padding is horribly broken software.
- saagarjha 6y agoI think you might be misunderstanding my comment, I’m not complaining about struct padding causing issues in my code, I’m saying the standard is wishy-washy about it. This can be problematic when you are doing things like memcpying a structure, or trying to zero it out before sending it somewhere else. (And, FWIW, there is no standard way to disable struct padding, and doing so will likely generate slower code anyways.)
- nwmcsween 6y agoHow is the standard not explicit? copying with padding doesn't need to copy the padding at all or can if it's faster, memcpy is a intrinsic the compiler can copy whatever it deems wrt padding.
- saagarjha 6y agoBecause there are certain cases in C11 where padding can be legally observed because it is defined to be set to zero–brace initialization, for example. It is unclear what happens in this case when you do anything with the memory other than read it (for example, storing to a structure member, based on the current reading of the standard, may make padding indeterminate again–plus, is "memcpy" a "read"?). See here for some of the questions raised: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1793.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1793.pdf
- asiachick 6y agoIs padding specified by the spec? Because if it's not then padding won't help you either since you don't know that your padding aligns with the compiler's. Rather AFAIK you need to write some compile time checks that what you think the compiler is going to do is what it does and fail compilation if doesn't and then add whatever compiler/platform/option specific code to get your stuff to match along with more tests.
- nwmcsween 6y agoYou would match by adding explicit padding bytes which would be archish specific (32 bit vs 64bit). A much better alternative to making life hard though is to just manually pack the struct