18

I understand that in the following line we are attempting to write to an invalid memory location. But this is actually a misaligned pointer also. Can someone explain what is a misaligned pointer and how is the following misaligned pointer ?

*(int*)0xffffffff = 0xbad;
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
gpuguy
  • 4,607
  • 17
  • 67
  • 125
  • 2
    Pointers in some architectures must fall on certain boundaries, *e.g.*, a 32-bit word boundary, so in that case the lower 2 bits of the pointer would need to be zero. – lurker Nov 25 '13 at 00:44

1 Answers1

26

Many architectures have a concept called alignment where the hardware is designed to operate on addresses that are multiples of the word size. For example, on a 32-bit processor, objects might be aligned to 32-bit boundaries (4 bytes), and on a 64-bit processor, objects might be aligned to 64-bit boundaries (8 bytes). An aligned pointer is one that points to an address that's a multiple of the word size, and an unaligned pointer is one that's not pointing to an address that's a multiple of the word size.

On most architectures, reading or writing unaligned pointers suffers some sort of penalty. On some processors, doing this causes a bus error, which usually terminates the program immediately. On others, such as x86, unaligned reads and writes are legal but suffer a performance penalty due to how the hardware is structured.

In your code, 0xFFFFFFFF = 232 - 1 is probably not aligned, since it's not a multiple of most common word sizes (it's not divisible by any power of two other than 20).

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065