uint32_t alignment on 64-bit?
Asked Answered
K

3

6

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?

Kerguelen answered 28/3, 2012 at 14:44 Comment(4)
What is the compiler and what is the architecture?Adellaadelle
Note that because of the way arrays work, the alignment requirement of uint32_t must be less than or equal to sizeof(uint32_t). Because of the requirement that there be no padding in uintN_t types, sizeof(uint32_t) * CHAR_BIT == 32. Anything else is non-conforming to C99. However, the alignment of your struct A is permitted by C99 to be bigger the biggest alignment of any member.Discombobulate
@steve So the individual uint32_t members can't be padded, but the overall structure can be? What would be the benefit of that? Two 32-bit members would give you 64-bit alignment as a matter of course...Kerguelen
@gct: I don't know what benefit your compiler feels there is. Presumably it's saying that accessing a 4-byte value on an 8-byte address is somehow more efficient, and so it wants b to be 8-aligned.Discombobulate
O
6

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.

Orazio answered 28/3, 2012 at 14:47 Comment(0)
M
2

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.

Manoff answered 28/3, 2012 at 14:46 Comment(1)
Strangely enough, if I do pack(1), then the two-element struct case above still gives me 16, but if I add one more uint32_t to it, I get 20...puzzlingKerguelen
Q
0

On linux with gcc and a 64 bit CPU I get what you would expect; the size of a struct with two short ints, is 4, two 32 bit ints is 8 and two 64 bit ints is 16.

Quincy answered 24/12, 2021 at 5:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.