1

Possible Duplicate:
Purpose of memory alignment

Why does structure or any memory allocations like int,char have to be word aligned. What advantage does it serve?

Update: Is the main reason, being if not memory aligned, there is possibility that part of a data type(int) is in one physical page and other part in another physical page?

I feel this is a stronger reason?

Community
  • 1
  • 1
Boolean
  • 14,266
  • 30
  • 88
  • 129

4 Answers4

2

If you think about how the machine is wired, it all makes sense.

Occasionally, people have tried to change this (Rambus, FBDIMM) but we keep coming back to wiring each bit in the DRAM array to it's identical bit on the CPU bus.

In the earlier days of computers, it was quite expensive to shift bits on the memory data bus to correct for misaligned accesses. Some machines didn't allow it all; the ones that did added a speed penalty. Some, like the original, at-the-time-super-fast and first-good- 64-bit-micro DEC-Alpha, actually did correct it but at the expense of a software trap!

The IA32 and x64 architectures have always fixed it up transparently, and with zillions of transistors on each chip they have the barrel shifters and other dedicated hardware to easily patch up misaligned references.

But, it still may interrupt the pipeline, it may take some sort of micro-trap; it isn't the "natural way".

The exact penalty is specific to the microarchitecture of the chip you are using. Portable code should assume that misaligned accesses are penalized. Some embedded CPU chips (Some Arm) actually don't error out but just do the wrong thing! I'm sincerely hoping that all of those are out-of-production.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
1

Memory access on many 32bit machines is much faster on 32bit boundaries, to access individual bytes the machine has to read a 32bit (4 byte) segment and then step into it

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
0

as Martin says it is faster ...

... and also some cpu architectures and some cpu instructions require it - will crash otherwise.

eg, some(?) ARM cpus will fault on non alignment. eg, MMX/SSE on x86/x64 require 16byte alignment.

SteelBytes
  • 6,905
  • 1
  • 26
  • 28
0

I had read the same somewhere(can't recollect : correct me if I am wrong) and supports steel`s comments:

The word i.e 2 bytes or 16x of data are generally used for those data operations which involved mul / div / signed operations...... major difference b/w x85 and x86

NirmalGeo
  • 773
  • 4
  • 12