Hannesh
Hannesh

Reputation: 7488

Why do we have alignment padding if memory is byte-addressable?

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?

Upvotes: 3

Views: 4593

Answers (2)

Paul R
Paul R

Reputation: 213029

On most architectures it is faster to perform read/write on naturally aligned data types. On some systems it will generate an exception (i.e. crash 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:

Upvotes: 4

Aamir Rind
Aamir Rind

Reputation: 39679

Taken from wikipedia:

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

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.

Upvotes: 3

Related Questions