What is Alignment and padding?

Placing data at addresses that are multiples of a number fixed for each type (alignment), and the unused bytes inserted between or after data items for that purpose (padding). In an environment where int is aligned on a 4-byte boundary, struct { char c; int i; char d; } gets 3 bytes after c and 3 bytes after d, for a size of 12 bytes. Reading or writing at a misaligned address is slower on some CPUs and raises an exception on others. Ordering members from the largest type down reduces padding.

Japanese name: アライメントとパディング

Alignment and padding appears in 2 practice questions across 2 topics, including ISA & Assembly, C Programming Basics.

Field: C Programming Basics

Try it: questions about Alignment and padding

In RISC-V, what can happen when the address of a 4-byte lw is not a multiple of 4 (misaligned)?

  1. AThe address is silently rounded to the next multiple of 4 and always read correctly at full speed
  2. BDepending on the implementation, it may raise an exception or be handled in hardware or software, possibly very slowly
  3. CThe low two address bits are simply ignored without error
Show answer and explanation

Answer: B. Depending on the implementation, it may raise an exception or be handled in hardware or software, possibly very slowly

A 4-byte item at an address that is a multiple of 4 can be read in one memory access. Crossing a boundary needs two accesses, so RISC-V lets each implementation either handle misaligned accesses in hardware or trap and leave them to software, which can be orders of magnitude slower. This is why compilers insert padding between struct members to keep them aligned.

Alignment and padding in the explanations

Questions that mention Alignment and padding (2)

  1. In RISC-V, what can happen when the address of a 4-byte lw is not a multiple of 4 (misaligned)?
  2. Assume a typical environment where char is 1 byte and int is 4 bytes, with int placed at addresses that are multiples of 4. Which of the following is the output when the code above is executed?

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

Related terms

struct (C structure) Array Bit-field Buffer overflow Dangling pointer Dynamic memory allocation Function pointer Integer promotion Macro (#define) Memory leak

Back to the glossary