union larger than largest struct

My union is larger than the largest struct, why is that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <stdio.h>

typedef struct
{
	UInt32					a;
	UInt32					b;
	UInt32					c;
}GndOrigin;

typedef struct
{
	UInt8					a; /*:8*/
	UInt8					b; /*:8*/
	UInt8					c; /*:8*/
	UInt8					d     :1;
	UInt8					e     :7;
	UInt16					f; /*:16*/
	UInt16					g;/*:16*/
	UInt16					h     :12;
	UInt16					i      :4;
	UInt16					j; /*:16*/
	UInt16					k     :3;
	UInt16					l      :13;
}UavInformation;

typedef union
{
	GndOrigin				   a;
	UavInformation		   b;
}DataSection;

int main()
{
	printf("\r\nsize of GndOrigin: %d\r\n",sizeof(GndOrigin));
	printf("\r\nsize of UavInformation: %d\r\n",sizeof(UavInformation));
	printf("\r\nsize of DataSection: %d\r\n",sizeof(DataSection));
        return 0;
}


size of GndOrigin: 12

size of UavInformation: 14

size of DataSection: 16
Last edited on
The size of the union has to account for both size and alignment requirements:

GndOrigin has a size of 12 but also has a 4-byte alignment requirement so that the UInt32 members are properly aligned on 4-byte boundaries. Note that 12 is a multiple of 4 so that if you have an array of GndOrigin objects, every entry is properly aligned.

UavInformation has a size of 14 and has a 2-byte alignment requirement to make every UInt16 properly aligned.

Since DataSection contains both GndOrigin and UavInformation, it must use the most restrictive alignment requirement, so DataSection should be 4-byte aligned.

If DataSection used only the size, it would be size 14. However, if we had an array of DataSection objects, array[0].a.a would be properly aligned at offset 0 but array[1].a.a would be improperly aligned at offset 14. Changing the size of DataSection to 16 forces proper alignment.

Note that there are some processors which can handle misaligned accesses (such as a 32-bit read which is not aligned on a 4-byte boundary), but there may or may not be a performance penalty for such an access. Many compilers provide an option for "packing" structs and arrays to ignore alignment requirements to pack the members as tightly as possible.
Topic archived. No new replies allowed.