# HG changeset patch # User Matti Hamalainen # Date 1211023307 -10800 # Node ID 785b606fd50481fb23c8beeed26de090998bae93 # Parent d4c5719d30d16559f0b161b9b4273ee00bd93545 Clarified and fixed the explanation of structure packing and unaligned memory access. diff -r d4c5719d30d1 -r 785b606fd504 HACKING --- a/HACKING Wed May 14 00:35:09 2008 +0200 +++ b/HACKING Sat May 17 14:21:47 2008 +0300 @@ -58,18 +58,19 @@ - When reading data from files, it's usually a BIG mistake to read structs directly from the stream! This is not portable, as C does not guarantee a struct not to have alignment padding (unless the struct is "packed", - but see below.) In effect sizeof(struct) on some platform may not be - equal to some other platform. + but see below.) In effect sizeof(struct), unless packed, on some platform + may not be equal to some other platform. - Some clever people might think that making struct "packed" via the - C packed qualifier would be a solution, but this will cause problems - on platforms which require words to be aligned in memory - so it - "works" on x86 (with performance penalty), but will fail with bus error - on elsewhere. + Making struct "packed" via the C packed qualifier or "#pragma pack()" is + a solution, but this must be used with care. Unaligned memory access + causes performance penalties, and may cause other, more serious problems + in some cases. For example, code written in assembler may not know about + the un-alignment, and may thus fail with 'bus errors' on platforms that + strictly required aligned data. - What you SHOULD do is read individual members of the struct one by one - from the stream. This may sound bothersome, but by doing so, your code - will be portable. + The 100% safe way is to read individual members of the struct one by one + from the stream. This may be bothersome, but by doing so, your code + will be portable for sure. - Always use Glib sized types for reading integer data from file streams.