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.

Share:
8,357

Related videos on Youtube

MABC
Author by

MABC

Updated on September 18, 2022

Comments

  • MABC
    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
    MABC over 10 years
    The 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
    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
    Alex over 10 years
    I think the boolean & version is preferred for performance reason as % imply multiplication or division duplicate?