Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uint32_t alignment on 64-bit?

I'm curious about the alignment of uint32_t types on 64-bit platforms. The spec says that uint32_t should be exactly the given bitwidth, which indeed it seems to be:

> printf("sizeof(uint32_t): %zd\n", sizeof(uint32_t));   
sizeof(uint32_t): 4

But then I have a struct:

typedef struct A {
    uint32_t a;
    uint32_t b;
} A;

But, surprisingly:

> printf("sizeof(A): %zd\n", sizeof(A));
sizeof(A): 16

Is uint32_t being 8-byte aligned for some reason? Is it really a 8-byte type underneath?

like image 497
gct Avatar asked Mar 28 '12 14:03

gct


2 Answers

It is entirely dependent on your compiler and architecture. In your case it looks as if the fields are indeed being 8-byte-aligned, perhaps for performance reasons.

like image 117
Graham Borland Avatar answered Nov 16 '22 23:11

Graham Borland


My guess is that by default everything on 64bit architecture will be aligned to 64bit boundaries same as on 32bit architecture everything is aligned to 4 bytes. You can specify packing pragma directives to get rid of the padding. For example

#pragma pack(0)

in gcc.

like image 2
MK. Avatar answered Nov 16 '22 22:11

MK.