Hacker News new | past | comments | ask | show | jobs | submit login

C structs are generally assumed to be laid out in the order defined with proper padding automatically inserted (as most platforms at best dislike unaligned accesses). Alignment information should only be necessary if you want to pack the structure or need to apply wider than standard alignment (e.g. need to align a 32 or 64b type to 128 bytes).

The one possible issue is that reading padding is UB (i think). But here there should be no padding: the struct is a pair number of bytes (alignment 1) and a word (alignment 2), which us aligned due to the previous, and the struct is if alignment 2.




Wider than standard alignment can be pretty important though. Especially for usage with SIMD instructions.


Sure but that has no relevance whatsoever to the article do the objection is irrelevant.


That's his point, you want to 1-align the struct to disable the padding to ensure the size of the structure is portable.


That makes no sense? There isn’t any padding, and if the bytes are not 8 bits it’ll never work anyway.


yeah C will be order defined in code, rust will reorder to save space unless you attribute it not to. interesting trivia a blind guy wrote the reordering code. if anyone knows his name please post.


Implemented in https://github.com/rust-lang/rust/pull/37429 ; his website seems to be https://ahicks.io/


The rust structure is defined as repr(C) so there is no reordering.


Does the C spec actually specify it needs to be in that order? Been awhile since I messed that that sort of thing. I know in practice they typically just put them in the same order and align on some sort of default packing depending on CPU. Usually to minimize on extra instructions. I have eeked out some extra perf on some CPUs and structs just by moving stuff around and making sure it fits into a cacheline. Sometimes the extra instructions are worth it to unpack some vars if you can get the data into a cacheline. But that depends on your data and usage.


Yes, it does




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: