Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C 64-bit Pointer Alignment

Are pointers on a 64-bit system still 4 byte aligned (similar to a double on a 32 bit system)? Or are they note 8 byte aligned?

For example, on a 64-bit system how big is the following data structure:

struct a {
    void* ptr;
    char myChar;
}

Would the pointer by 8 byte aligned, causing 7 bytes of padding for the character (total = 8 + 8 = 16)? Or would the pointer be 4 byte aligned (4 bytes + 4 bytes) causing 3 bytes of padding (total = 4 + 4 + 4 = 12)?

Thanks, Ryan

like image 922
DuneBug Avatar asked Mar 24 '10 07:03

DuneBug


People also ask

What is 64 bit alignment?

64-bit aligned is 8 bytes aligned). A memory access is said to be aligned when the data being accessed is n bytes long and the datum address is n-byte aligned. When a memory access is not aligned, it is said to be misaligned. Note that by definition byte memory accesses are always aligned.

What is alignment in rust?

The alignment of a value specifies what addresses are valid to store the value at. A value of alignment n must only be stored at an address that is a multiple of n. For example, a value with an alignment of 2 must be stored at an even address, while a value with an alignment of 1 can be stored at any address.

What is align in c++?

std::size_t& space ); (since C++11) Given a pointer ptr to a buffer of size space , returns a pointer aligned by the specified alignment for size number of bytes and decreases space argument by the number of bytes used for alignment. The first aligned address is returned.

What is aligned pointer?

Aligned Pointer means that pointer with adjacent memory location that can be accessed by a adding a constant and its multiples. for char a[5] = "12345"; here a is constant pointer if you and the size of char to it every time you can access the next chracter that is, a +sizeofchar will access 2.


1 Answers

Data alignment and packing are implementation specific, and can be usually changed from compiler settings (or even with pragmas).

However assuming you're using default settings, on most (if not all) compilers the structure should end up being 16 bytes total. The reason is because computers reads a data chunk with size of its native word size (which is 8 bytes in 64-bit system). If it were to pad it to 4 byte offsets, the next structure would not be properly padded to 64-bit boundary. For example in case of a arr[2], the second element of the array would start at 12-byte offset, which isn't at the native byte boundary of the machine.

like image 104
reko_t Avatar answered Sep 21 '22 18:09

reko_t