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;
1
  • 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. Commented Nov 25, 2013 at 0:44

1 Answer 1

29

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.