6 ms·
TL;DR: to get smaller structures, don't do stuff like this: struct foo { char a; int b; char c; int d; }; but this: struct foo {
by kazinator 10y ago
TL;DR: to get smaller structures, don't do stuff like this:
struct foo {
char a;
int b;
char c;
int d;
};
but this:
struct foo {
int b; // or int b, c;
int c;
char a;
char c;
};
Basically if you sort the types by size in reverse descending order, you get optimal packing without messing with compiler-specific packing extensions that skew alignment and possibly bloat code.
The worst that you will get is padding at the end of the structure so that if two or more of them are arrayed, the first member is correctly aligned at all the array indices.
- vonmoltke 10y ago> The worst that you will get is padding at the end of the structure so that if two or more of them are arrayed, the first member is correctly aligned at all the array indices. This is not guaranteed. If you want to ensure all array member starting addresses are aligned for all compilers and platforms you need to add explicit dead space. You should also be using the fixed-width numeric types.
- kazinator 10y agoIt's not guaranteed (as in "money back" or whatever). It's merely required by ISO C for conformance. If a struct is declared like this: struct foo { whatever_type_t first_member; // ... }; then an array of this type can also be declared: struct foo farray[42]; A conforming ISO C implementation has to ensure that farray[1].first_member, and farray[2].first_member, and so on, are all allocated such that they meet the alignment requirements fro whatever_type_t. It cannot be that farray[0].first_member is accessible, but farray[1].first_member throws an alignment exception or whatever. Programmers should not have to do anything to ensure this. So, if necessary, padding is added at the end of struct foo to make this alignment happen. In practice, compilers add the padding even if it's not required for at least two reasons: performance (misaligned accesses, though supported, may be slow) and compatibility (having the structure look the same across multiple architectures supported by the same compiler, at most modulo byte order). > You should also be using the fixed-width numeric types. I'm not aware that C provides any other, currently. Though you can simulate them with libraries, of course.
- david-given 10y agoI agree with you, but it'd be nicer if it were easier to figure this out from the standard --- either I'm missing something or else you have to infer it from reading between the lines: 6.7.2.1 para 15 of the C11 standard: Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. 6.7.2.1 para 17: There may be unnamed padding at the end of a structure or union. 6.2.5 para 20: An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type. http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1570.pdf http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1570.pdf So, on a platform with strict alignment, in order to achieve contiguous packing of structures (required by the last) and to achieve each structure member having a valid pointer (required by the first) the implementation must add enough optional padding (allowed by the middle) to make the size of the structure aligned. > You should also be using the fixed-width numeric types. I believe the parent is referring to the int8_t, int16_t types rather than the implementation-defined int, short, long types here.
- vonmoltke 10y ago> I agree with you, but it'd be nicer if it were easier to figure this out from the standard --- either I'm missing something or else you have to infer it from reading between the lines: > So, on a platform with strict alignment, in order to achieve contiguous packing of structures (required by the last) and to achieve each structure member having a valid pointer (required by the first) the implementation must add enough optional padding (allowed by the middle) to make the size of the structure aligned. It's not in the standard per se. It's a requirement for machine code to function on certain platforms. The standard basically just says that in all cases compilers have to generate machine code that works properly. It is imposed by the designers of the processor, not the C standard. > I believe the parent is referring to the int8_t, int16_t types rather than the implementation-defined int, short, long types here. This is indeed what I was talking about.
- 10y ago
- blaisio 10y agoCan you give an example of a compiler and platform where this isn't true? I thought it was part of the standard, and I've never seen C code that didn't make the assumption that this is true.
- vonmoltke 10y agoIIRC, icc does not normally pad structures, since x86-64 supports unaligned loads fairly well. xlc on POWER generally tries to do what kazinator stated above because unaligned loads are expensive, if even possible, on those platforms.
- dysoco 10y agoAlright this might be a stupid question, but if packing is about the order in which the fields are arranged... shouldn't the compiler optimize that? I mean, it does much more complex optimizations already doesn't it?
- Arnavion 10y agoThe language spec prevents it from doing so for ABI reasons. The optimization is present in other languages that did not start with this restriction, but it's too late for C now.
- valarauca1 10y ago>The optimization is present in other languages that did not start with this restriction, but it's too late for C now. Which? .NET is the only one I could find that appears to do some from of smart packing [1] The new hotness languages behave like: Go doesn't sort by size. It packs to the byte, but guarantees structures within structures will start on the 32/64bit boundary (depending on 32/64bit system) so it'll pad for them. Rust ignores field size and just aligns to the 32bit boundary, unless you trigger `#[repr(C)]` which will pack like C. Rust doesn't give any guarantees about a structure is laid out to be perfectly honest. C++, NIM, D. I can find no reference on Crystal except that you can opt into C behavior. So I don't know what default is. [1] https://msdn.microsoft.com/en-us/library/ms253935(v=vs.80).aspx https://msdn.microsoft.com/en-us/library/ms253935(v=vs.80).a...
- ygra 10y agoThe linked site explains structure packing for C/C++ and the related compiler options. It has nothing to do with the CLR.
- dbaupp 10y agoRust doesn't ignore field size nor does it align to any particular boundary. E.g. struct Foo { x: u8 } is one byte and has alignment 1, and similarly struct Bar { x: u8, y: i16 } is 4 bytes and has alignment 2. The compiler doesn't give guarantees about structure layout so that it is able to reduce the size by reordering fields.
- throwanem 10y ago> reverse descending order ...so, ascending order?
- Grishnakh 10y agoWouldn't it make sense for the compiler to automatically optimize stuff like this? The compiler knows all about the underlying architecture the code will be running on, so it's best positioned to determine how to order data for optimal efficiency.
- to3m 10y agoThe C rules don't permit it. Putting fields in the order specified is not the worst possible default. (The option would be nice, though... most of the time, you don't care.)
- nwmcsween 10y agoNo as you might be poking hardware and having the compiler at best make something not work or at worst brick hardware is not good. Compilers can earn on padding, most with -Wpadding