Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a misaligned pointer ?

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;
like image 253
gpuguy Avatar asked Nov 25 '13 00:11

gpuguy


1 Answers

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!

like image 128
templatetypedef Avatar answered Oct 02 '22 10:10

templatetypedef