comparison HACKING @ 4549:785b606fd504

Clarified and fixed the explanation of structure packing and unaligned memory access.
author Matti Hamalainen <ccr@tnsp.org>
date Sat, 17 May 2008 14:21:47 +0300
parents 8e8a82c9311a
children 10cfc41149ff
comparison
equal deleted inserted replaced
4546:d4c5719d30d1 4549:785b606fd504
56 56
57 57
58 - When reading data from files, it's usually a BIG mistake to read structs 58 - When reading data from files, it's usually a BIG mistake to read structs
59 directly from the stream! This is not portable, as C does not guarantee 59 directly from the stream! This is not portable, as C does not guarantee
60 a struct not to have alignment padding (unless the struct is "packed", 60 a struct not to have alignment padding (unless the struct is "packed",
61 but see below.) In effect sizeof(struct) on some platform may not be 61 but see below.) In effect sizeof(struct), unless packed, on some platform
62 equal to some other platform. 62 may not be equal to some other platform.
63 63
64 Some clever people might think that making struct "packed" via the 64 Making struct "packed" via the C packed qualifier or "#pragma pack()" is
65 C packed qualifier would be a solution, but this will cause problems 65 a solution, but this must be used with care. Unaligned memory access
66 on platforms which require words to be aligned in memory - so it 66 causes performance penalties, and may cause other, more serious problems
67 "works" on x86 (with performance penalty), but will fail with bus error 67 in some cases. For example, code written in assembler may not know about
68 on elsewhere. 68 the un-alignment, and may thus fail with 'bus errors' on platforms that
69 strictly required aligned data.
69 70
70 What you SHOULD do is read individual members of the struct one by one 71 The 100% safe way is to read individual members of the struct one by one
71 from the stream. This may sound bothersome, but by doing so, your code 72 from the stream. This may be bothersome, but by doing so, your code
72 will be portable. 73 will be portable for sure.
73 74
74 75
75 - Always use Glib sized types for reading integer data from file streams. 76 - Always use Glib sized types for reading integer data from file streams.
76 Using plain C types (like 'long int' for example) is not wise, because 77 Using plain C types (like 'long int' for example) is not wise, because
77 they may be of different size on different platforms depending on the 78 they may be of different size on different platforms depending on the