Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When malloc returns, what does 8-byte alignment mean?

In libc's malloc(x), the function is said to return a pointer to a memory region of at least x bytes and the pointer is aligned to 8 bytes. What does this alignment mean? THank you.

like image 701
cody Avatar asked Mar 14 '13 23:03

cody


People also ask

What does it mean to be 8 byte aligned?

An object that is "8 bytes aligned" is stored at a memory address that is a multiple of 8. Many CPUs will only load some data types from aligned locations; on other CPUs such access is just faster. There's also several other possible reasons for using memory alignment - without seeing the code it's hard to say why.

What is the alignment of malloc?

new and malloc, by default, align address to 8 bytes (x86) or 16 bytes (x64), which is the optimal for most complex data.

What does it mean to be byte aligned?

A memory address a is said to be n-byte aligned when a is a multiple of n (where n is a power of 2). In this context, a byte is the smallest unit of memory access, i.e. each memory address specifies a different byte.

Is malloc 16 byte aligned?

The GNU documentation states that malloc is aligned to 16 byte multiples on 64 bit systems.


2 Answers

It means that the pointed address mod 8 is 0:

pointer % 8 == 0

This can be important for low level operations where it may impact correctness or efficiency. See also this answer.

like image 56
perreal Avatar answered Sep 22 '22 02:09

perreal


It means that the memory starts on an address that is a multiple of 8.

As for why you would even care: For memory that's not aligned, the CPU sometimes requires two accesses to read it all. In some cases, it won't even try and will just throw an error. The mention of "aligned to 8 bytes" is so that the caller knows whether it'll have to do any fudging of the pointer or not.

(Usually, you won't care -- the compiler takes care of most of the alignment issues for you. But the info's there in case you need it for some reason.)

like image 36
cHao Avatar answered Sep 18 '22 02:09

cHao