
Question:
Since we can address every byte of memory individually, why do compilers take extra care to make sure that structs and it's members align to 32-bit borders in memory? I could be wrong here, but on a 32-bit system, is it not just as fast to get 4 bytes starting from say 0x0800, as it is from 0x0801?
Answer1:On most architectures it is faster to perform read/write on naturally aligned data types. On <em>some</em> systems it will generate an exception (i.e. <em>crash</em> in most cases) if you try to access certain types when they are misaligned. So in general you always want to maintain natural alignment unless you have a very good reason not to.
See also related SO questions and answers:
<ul><li><a href="https://stackoverflow.com/questions/381244/purpose-of-memory-alignment" rel="nofollow">Purpose of memory alignment</a>
</li> <li><a href="https://stackoverflow.com/questions/2006216/why-is-data-structure-alignment-important-for-performance" rel="nofollow">why is data structure alignment important for performance?</a>
</li> <li><a href="https://stackoverflow.com/questions/1496848/does-unaligned-memory-access-always-cause-bus-errors" rel="nofollow">Does unaligned memory access always cause bus errors?</a>
</li> </ul>Answer2:Taken from <a href="http://en.wikipedia.org/wiki/Data_structure_alignment" rel="nofollow">wikipedia</a>:
<blockquote>For example, when the computer's word size is 4 bytes (a byte meaning 8 bits), the data to be read should be at a memory offset which is some multiple of 4. When this is not the case, e.g. the data starts at the 14th byte instead of the 16th byte, then the computer has to read two 4-byte chunks and do some calculation before the requested data has been read, or it may generate an alignment fault. Even though the previous data structure ends at the 14th byte, the next data structure should start at the 16th byte. Two padding bytes are inserted between the two data structures to align the next data structure to the 16th byte
</blockquote>The memory has to be multiple of 4 bytes
for faster access and to reduce computation
for better performance
.
so if the memory is address byte addressable usually of 4 bytes chunks in most of cases then we know where the next address is going to start e.g. as explained above also if you end up with 14 bytes
(that should be 16 bytes 4*4 = 16) then you know how much padding you have to use 16-14 = 2 bytes padding
. that is why padding is used in misaligned memory.