Know when a memory address is aligned or unaligned
8,357
In short an unaligned address is one of a simple type (e.g., integer or floating point variable) that is bigger than (usually) a byte and not evenly divisible by the size of the data type one tries to read.
Address % Size != 0
Say you have this memory range and read 4 bytes:
+---------- 8 % 4 = 0, OK
|
______+______
| |
... 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...
--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+--
* | @ | @ | @ | @ | * | * | * | * | @ | @ | @ | @ | * | * | *
--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+--
|_______.______|
|
+--- 10 % 4 = 2, Unaligned
More on the matter in Documentation/unaligned-memory-access.txt.
Related videos on Youtube
Author by
MABC
Updated on September 18, 2022Comments
-
MABC almost 2 years
Im getting kernel oops because ppp driver is trying to access to unaligned address (there is a pointer pointing to unaligned address). Im not sure about the meaning of unaligned address. It means not multiple or 4 or out of RAM scope? If my system has a bus 32-bits wide, given an address how can i know if its aligned or unaligned?
-
MABC over 10 yearsThe pointer store a virtual memory address, so linux check the unaligned address in virtual memory? If so, variables are stored always in aligned physical address too?
-
peterph over 10 years@user2119381 No. Since memory on most systems is paged with pagesizes from 4K up and alignment is usually matter of orders of magnitude less (typically bus width, i.e. 16/32/64/128b) alignedness is identical for virtual and physical addresses.
-
Alex over 10 yearsI think the boolean
&
version is preferred for performance reason as%
imply multiplication or division duplicate?